使用包含与号的URL将XML加载到XDocument [英] Loading XML to an XDocument with a URL containing an ampersand
问题描述
XDocument xd = XDocument.Load("http://www.google.com/ig/api?weather=vilnius&hl=lt");
在调用Load()
方法时,包含URL的字符串中的&符号不是受支持的字符.发生此错误:
The ampersand &
isn't a supported character in a string containing a URL when calling the Load()
method. This error occurs:
未处理XmlException:给定编码中的无效字符
XmlException was unhandled: Invalid character in the given encoding
如何将XML从URL加载到XDocument中,该URL的查询字符串中是否带有&符号?
How can you load XML from a URL into an XDocument where the URL has an ampersand in the querystring?
推荐答案
您需要对其进行URL编码为&
:
You need to URL-encode it as &
:
XDocument xd = XDocument.Load(
"http://www.google.com/ig/api?weather=vilnius&hl=lt");
您也许可以摆脱使用WebUtility.HtmlEncode
自动执行此转换的麻烦;但是,请注意,这不是该方法的预期用途.
You might be able to get away with using WebUtility.HtmlEncode
to perform this conversion automatically; however, be careful that this is not the intended use of that method.
编辑:此处的真正问题与&符无关,而是与Google使用自定义编码对XML文档进行编码而未声明它的方式有关. (仅在特殊情况下(例如(X)HTML的<a href="…" />
元素时),才需要对&符号进行编码.请阅读 URL中的&符号以进行快速说明.)
Edit: The real issue here has nothing to do with the ampersand, but with the way Google is encoding the XML document using a custom encoding and failing to declare it. (Ampersands only need to be encoded when they occur within special contexts, such as the <a href="…" />
element of (X)HTML. Read Ampersands (&'s) in URLs for a quick explanation.)
由于XML声明未指定编码,因此XDocument.Load
在内部回退到XML规范要求的默认UTF-8编码,这与实际数据不兼容.
Since the XML declaration does not specify the encoding, XDocument.Load
is internally falling back to default UTF-8 encoding as required by XML specification, which is incompatible with the actual data.
为避免此问题,您可以使用以下示例获取原始数据并对其进行手动解码.我不知道该编码是否真的是Windows-1252,因此您可能需要尝试其他编码.
To circumvent this issue, you can fetch the raw data and decode it manually using the sample below. I don’t know whether the encoding really is Windows-1252, so you might need to experiment a bit with other encodings.
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);
这篇关于使用包含与号的URL将XML加载到XDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!