XML url 中的 & 符号未通过

Nic*_*ahn 4 .net c# xml xml-serialization xmlserializer

我很难解决 URL 中与号 (&) 的这个小问题......我正在序列化 XML,如下所示......

    var ser = new XmlSerializer(typeof(response));
    using (var reader = XmlReader.Create(url))
    {
        response employeeResults = (response)ser.Deserialize(reader); //<<error when i pass with ampersand
    }
Run Code Online (Sandbox Code Playgroud)

如果&url 中没有,上面的代码工作正常,否则它会抛出一个错误(见下文)

我没有问题序列化这个网址:

http://api.host.com/api/employees.xml/?&search=john
Run Code Online (Sandbox Code Playgroud)

这个网址有问题:

http://api.host.com/api/employees.xml/?&max=20&page=10
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

`There is an error in XML document (1, 389).`
Run Code Online (Sandbox Code Playgroud)

PS:我确实尝试过传球&#038;,也尝试过&#38or#026&amp;- 没有运气。

Kir*_*huk 5

此 XML 格式不正确:

<?xml version="1.0"?>
<response xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Api">
  <meta>
    <status>200</status>
    <message />
    <resultSet>
      <Checked>true</Checked>
    </resultSet>
    <pagination>
      <count>1</count>
      <page>1</page>
      <max>1</max>
      <curUri>http://api.host.com/employee.xml/?&max=5</curUri>
      <prevUri i:nil="true"/>
      <nextUri>http://api.host.com/employee.xml/?&max=5&page=2</nextUri>
    </pagination>
  </meta>
  <results i:type="ArrayOfemployeeItem">
    <empItem>
      <Id>CTR3242</Id>
      <name>john</name>
      ......
    </empItem>
  </results>
</response>
Run Code Online (Sandbox Code Playgroud)

您必须转义&字符或将整个字符串放入CDATA,例如:

<?xml version="1.0"?>
<response xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Api">
  <meta>
    <status>200</status>
    <message />
    <resultSet>
      <Checked>true</Checked>
    </resultSet>
    <pagination>
      <count>1</count>
      <page>1</page>
      <max>1</max>
      <curUri><![CDATA[http://api.host.com/employee.xml/?&max=5]]></curUri>
      <prevUri i:nil="true"/>
      <nextUri><![CDATA[http://api.host.com/employee.xml/?&max=5&page=2]]></nextUri>
    </pagination>
  </meta>
  <results i:type="ArrayOfemployeeItem">
    <empItem>
      <Id>CTR3242</Id>
      <name>john</name>
      ......
    </empItem>
  </results>
</response>
Run Code Online (Sandbox Code Playgroud)

如果您正在处理某些第三方系统并且无法获得正确的 XML 响应,则必须进行一些预处理。

也许最简单的方法就是&&amp;usingstring.Replace方法替换 all 。

或者使用这个正则表达式&(?!amp;)来替换所有&排除正确的,比如&amp;.

  • +1(在“无效的 XML”上进行任何类型的字符串替换以使其格式良好通常是个坏主意,强制格式良好的 XML 要好得多)。[XML 规范](http://www.w3.org/TR/2000/REC-xml-20001006#syntax) 是查找 XML 规范的最佳位置。请参阅 http://stackoverflow.com/questions/1328538/how-do-i-escape-ampersands-in-xml 中的参考资料 (2认同)