使用包含&符号的URL将XML加载到XDocument

Wiz*_*ard 1 c# linq-to-xml

XDocument xd = XDocument.Load("http://www.google.com/ig/api?weather=vilnius&hl=lt");
Run Code Online (Sandbox Code Playgroud)

&调用Load()方法时,&符号不是包含URL的字符串中的受支持字符.发生此错误:

未处理XmlException:给定编码中的字符无效

如何将URL从URL加载到XDocument中,其中URL在查询字符串中有&符号?

Dou*_*las 8

您需要对其进行URL编码&:

XDocument xd = XDocument.Load(
    "http://www.google.com/ig/api?weather=vilnius&hl=lt");
Run Code Online (Sandbox Code Playgroud)

您可以使用WebUtility.HtmlEncode自动执行此转换; 但是,请注意,这不是该方法的预期用途.

编辑:这里的真正问题与&符号无关,但是Google使用自定义编码对XML文档进行编码并且无法声明它.(&符号只有在特殊情境中出现时才需要进行编码,例如<a href="…" />(X)HTML 的元素.在URL中读取&符号(&),以便快速解释.)

由于XML声明未指定编码,XDocument.Load因此内部回退到XML规范所要求的默认UTF-8编码,这与实际数据不兼容.

要解决此问题,您可以使用下面的示例手动获取原始数据并对其进行解码.我不知道编码是否真的是Windows-1252,因此您可能需要对其他编码进行一些实验.

string url = "http://www.google.com/ig/api?weather=vilnius&hl=lt";
byte[] data;
using (WebClient webClient = new WebClient())
    data = webClient.DownloadData(url);

string str = Encoding.GetEncoding("Windows-1252").GetString(data);
XDocument xd = XDocument.Parse(str);
Run Code Online (Sandbox Code Playgroud)