.NET: How to insert XML document into SQL Server

后端 未结 4 475
野性不改
野性不改 2021-01-04 18:27

I want to insert arbitrary XML into SQL Server. The XML is contained in an XmlDocument object.

The column I want to insert into is either nvarchar

4条回答
  •  被撕碎了的回忆
    2021-01-04 18:54

    Better late than never... I think you're looking for something like this:

    void SaveXmlToDatabase(DbConnection connection,
          XmlDocument xmlToSave,
          String tableName, String columnName)
    {
       String sql = "INSERT INTO "+tableName+" ("+columnName+") 
              VALUES (@XmlVal)";
    
       using (DbCommand command = connection.CreateCommand())
       {
          command.CommandText = sql;
          command.Parameters.AddWithValue("XmlVal", new SqlXml(new XmlNodeReader(xmlToSave)));
    
          DbTransaction trans = connection.BeginTransaction();
          try
          {
             command.ExecuteNonQuery();
             trans.Commit();
          }
          catch (Exception)
          {
             trans.Rollback();
             throw;
          }
       }
    }
    

    The XmlNodeReader object traverses and properly encodes the XmlDocument (or any other XmlNode), and the SqlXml object encapsulates that into the SqlDbType suitable for use with the parameter. This is safer and probably more efficient than using a string intermediary.

提交回复
热议问题