尝试解析XML时,我得到一个引用无效标记的异常
来自网址的HTML回复:
<?xml version="1.0" encoding="UTF-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/server/ResponseSchema" version="1.01">
<status success="true" statusCode="2000"/>
<readCalls>
<classify id="Classify">
<classification textCoverage="0.849057">
<class className="negative" p="0.567908"/>
<class className="positive" p="0.432092"/>
</classification>
</classify>
</readCalls>
</uclassify>
代码:
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var stream = myHttpWebResponse.GetResponseStream();
var reader = new StreamReader(stream);
string html = reader.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(html);
string negative = doc.SelectSingleNode("/uclassify/readCalls/classify/classification/class[1]@p").ToString();
string positive = doc.SelectSingleNode("/uclassify/readCalls/classify/classification/class[2]@p").ToString();
我真的不明白为什么它不起作用。任何帮助,将不胜感激。
答案 0 :(得分:3)
xml中有一个默认的命名空间,在xpath中是必需的。
XmlNamespaceManager oManager = new XmlNamespaceManager(new NameTable());
oManager.AddNamespace("ns", "http://api.uclassify.com/1/server/ResponseSchema");
doc.SelectSingleNode("/ns:uclassify/ns:readCalls/ns:classify/ns:classification/ns:class[1]/@p",oManager);
虽然我会使用LINQ2XML
XDocument doc=XDocument.Load(stream);
var pList=doc.Descendants()
.Elements(x=>x.Name.LocalName=="class")
.Select(a=>
new
{
className=a.Attribute("className").Value,
p=a.Attribute("p").Value
});
您现在可以遍历pList
foreach(var p in pList)
{
p.className;
p.p;
}
答案 1 :(得分:1)
你不应该在某处声明命名空间吗?您获得的XML响应具有默认名称空间xmlns="http://api.uclassify.com/1/server/ResponseSchema"
。
另外,请务必在XPath中添加/
之前的@p
:
/uclassify/readCalls/classify/classification/class[1]/@p