1

我尝试使用以下代码获取 xml 文件:

HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
string xml = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    xml = sr.ReadToEnd();
}

XmlDocument xmlDoc = new XmlDocument();
//xml = xml.Replace((char)(0x1F), ' ');
xmlDoc.LoadXml(xml);

但我得到如下异常:

' ', hexadecimal value 0x1F, is an invalid character. Line 1, position 1.

因此,根据stackoverflow上的许多类似问题,我尝试添加此注释行,但随后出现异常:

Data at the root level is invalid. Line 1, position 2.

怎么了?

4

1 回答 1

4

假设应用于 XML 的压缩是 GZip,您可以像这样解压缩 XML:

HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
string xml = string.Empty;
using (GZipStream gzip = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
using (StreamReader sr = new StreamReader(gzip))
{
  xml = sr.ReadToEnd();
}

XmlDocument xmlDoc = new XmlDocument();
//xml = xml.Replace((char)(0x1F), ' ');
xmlDoc.LoadXml(xml);

如果 GZipStream 无法解压缩 XML,则必须将其替换为适当的解压缩流。

于 2012-09-17T21:54:02.143 回答