gpt4 book ai didi

xml - 在 Windows Phone 中使用 HttpWebRequest 获取 xml

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

我正在使用 httpwebrequest 来获取一些 xml 文档,代码如下。当我打电话时

HttpGetMethod http = new HttpGetMethod();
http.Request("http://sample.com/xml.php");

它工作正常,然后我使用

XDocument document = XDocument.Parse(xml);

XElement element = document.Element("statuses");
IEnumerable<XElement> statusesElements = element.Elements("status");

foreach (var elx in statusesElements)
{}

解析xml文档。但是有时会导致异常,然后我跟踪发现返回的xml字符串中包含“e48”(我正在使用Fiddler查找返回的xml字符串),如图所示。但是我想不通原因,好奇怪,“e48”是什么?有人可以帮忙吗?

谢谢。

enter image description here

public class HttpGetMethod
{
public WebCallBack CallBack;

public void Request(string url)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
IAsyncResult result = null;

result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
}

private void ResponseCallback(IAsyncResult result)
{
try
{
var request = (HttpWebRequest)result.AsyncState;
var response = request.EndGetResponse(result);

using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{

if (CallBack != null)
{
var str = reader.ReadToEnd();
CallBack(str);
}
}
}
}
catch (Exception ex)
{
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
CallBack(ex.ToString());
});
}
}
}

调试输出为:

A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
System.Xml.XmlException: '', hexadecimal value 0x0C, is an invalid character. Line 897, position 14.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString, String[] args)
at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, Int32 res, String resString, String[] args)
at System.Xml.XmlTextReaderImpl.ThrowInvalidChar(Char[] data, Int32 length, Int32 invCharPos)
at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type, Int32& outStartPos, Int32& outEndPos)
at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type)
at System.Xml.XmlTextReaderImpl.ParseCData()
at System.Xml.XmlTextReaderImpl.Parse

这是 Fiddle 的原始响应:

enter image description here

最佳答案

IMO 在这种特定情况下使用正则表达式,例如“^[^<]*”

String result = Regex.Replace(htmlDocument, @"^[^<]*", System.String.Empty, RegexOptions.Singleline);

删除前面的垃圾字符

关于xml - 在 Windows Phone 中使用 HttpWebRequest 获取 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9441913/

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