我尝试使用以下代码获取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.
怎么了?
答案 0 :(得分: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,则必须用适当的解压缩流替换它。