StringWriter.ToString()正在破坏xml c#

本文关键字:xml ToString StringWriter | 更新日期: 2023-09-27 17:54:38

我有一个类数组,我将传递给XML,以便稍后将其发送到SQL Server存储过程。问题是,当我执行StringWriter时,它会添加一些出现在最终XML中的字符(=')。

我的代码如下:
  public XmlDocument ToXML(object obj_to_xml)
{
    string str_XML;
    XmlDocument xml = new XmlDocument();
    var stringwriter = new System.IO.StringWriter();
    var serializer = new XmlSerializer(obj_to_xml.GetType());
    serializer.Serialize(stringwriter, obj_to_xml);**
    //at this point the format is correct, for example stringwriter contains: 
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfRegistroPrestamo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <RegistroPrestamo>
    <Id>1</Id>
    <Cedula>8-834-789</Cedula>
    <Nombre>Amarillos</Nombre>
    <Apellido>Perez</Apellido>
  </RegistroPrestamo>
  <RegistroPrestamo>
    <Id>0</Id>
    <Cedula />
    <Nombre />
    <Apellido />
  </RegistroPrestamo>
</ArrayOfRegistroPrestamo>
    //the problem comes with this line
    xml.LoadXml(stringwriter.ToString());
    //final XML looks like this: 
<?xml version='"1.0'" encoding='"utf-16'"?>
<ArrayOfRegistroPrestamo xmlns:xsd='"http://www.w3.org/2001/XMLSchema'" xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance'">
  <RegistroPrestamo>
    <Id>1</Id>
    <Cedula>8-834-789</Cedula>
    <Nombre>Amarillos</Nombre>
    <Apellido>Perez</Apellido>
  </RegistroPrestamo>
  <RegistroPrestamo>
    <Id>0</Id>
    <Cedula />
    <Nombre />
    <Apellido />
  </RegistroPrestamo>
</ArrayOfRegistroPrestamo>
    return xml;
}

当SQL Server试图解析XML代码时:

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "P_Save_Procedure";
cmd.Parameters.Add("@Registros", SqlDbType.Xml).Value = xml;

存储过程文本

Create procedure [dbo].[P_Save_Procedure]
(@Registros as xml)
as
begin
    select distinct 'Id' = x.v.value('Id[1]', 'Int')
    from @Registros.nodes('/ArrayOfRegistroPrestamo/RegistroPrestamo') x(v)
end

我得到了错误:

犯罪。9413,州1 16层,4号线XML解析:第1行,字符37;它需要一个字符串字面值

如果我用正确的XML版本手动调用SP:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfRegistroPrestamo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <RegistroPrestamo>
    <Id>1</Id>
    <Cedula>8-834-789</Cedula>
    <Nombre>Amarillos</Nombre>
    <Apellido>Perez</Apellido>
  </RegistroPrestamo>
  <RegistroPrestamo>
    <Id>0</Id>
    <Cedula />
    <Nombre />
    <Apellido />
  </RegistroPrestamo>
</ArrayOfRegistroPrestamo>

结果是预期的。

已经花了2天时间试图找到一种方法来获得XML的正确sintax,但一无所获。

StringWriter.ToString()正在破坏xml c#

见:

DoNotEscapeUriAttributes