我正在尝试将ASP.NET
Web API中的XML响应读入DataSet
,以便我可以将其绑定到DropDownList
。但是,在阅读回复时,我遇到了Data at the root level is invalid. Line 1, position 1.
Snipp:
WebRequest request = WebRequest.Create("EndPointURL");
request.Method = "GET";
WebResponse response = request.GetResponse();
DataSet ds = new DataSet();
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
ds.ReadXml(rdr); //EXCEPTION Data at the root level is invalid. Line 1, position 1.
}
XML响应示例:
<ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MySchema">
<Person>
<Address1 xmlns="http://schemas.datacontract.org/2004/07/ClassSchema">123 Main Street</Address1>
<Address2 xmlns="http://schemas.datacontract.org/2004/07/ClassSchema"">None</Address2>
...FOR BREVITY
</Person>
<Person>
..FOR BREVITY
</Person>
.
.
.
</ArrayOfPerson>
我已经成功地调用了API的其他端点,所以我有点难过。我在Line 1, position 1
看不到任何看似无效的XML字符的内容。什么可能抛出错误?
答案 0 :(得分:0)
尝试:
ReadXml(XmlReader)
像这样:
XmlTextReader reader = new XmlTextReader(rdr);
ds.ReadXml(reader);
答案 1 :(得分:0)
听起来你可能使用了错误的编码。您可以尝试从HttpWebResponse
:
var ds = new DataSet();
WebRequest request = WebRequest.Create(requestUriString);
request.Method = "GET";
using (var response = (System.Net.HttpWebResponse)request.GetResponse())
{
// get correct charset and encoding from the server's header
Encoding encoding;
try
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
catch
{
encoding = Encoding.UTF8;
}
using (var rdr = new StreamReader(response.GetResponseStream(), encoding))
{
ds.ReadXml(rdr);
}
}
请注意,这是复杂答案的简化版本:Encoding problem with HttpWebResponse。这些答案建议从返回的HTML中挑选实际编码,并在需要时重新加载流。如果确实需要,可以尝试从XML declaration中选择编码来做类似的事情。