gpt4 book ai didi

c# - XML url 中的 & 符号未通过

转载 作者:数据小太阳 更新时间:2023-10-29 02:24:04 24 4
gpt4 key购买 nike

我很难解决 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
}

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

我序列化这个 url 没有问题:

http://api.host.com/api/employees.xml/?&search=john

我遇到这个 url 的问题:

http://api.host.com/api/employees.xml/?&max=20&page=10

我得到的错误是:

`There is an error in XML document (1, 389).`

PS:我确实试过传递 & 也试过 &#026& - 运气不好。

最佳答案

此 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>

您必须转义 & 字符或将整个字符串放入 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>

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

也许最简单的方法是使用 string.Replace 方法将所有 & 替换为 &

或者使用此正则表达式 &(?!amp;) 替换所有 &,但不包括正确的 &

关于c# - XML url 中的 & 符号未通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19696061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com