[英]How to Parse Nested XML Nodes in C#
我是C#的新手,但似乎這應該很簡單。 我正在嘗試解析從網絡供稿返回的XML字符串,如下所示:
<autnresponse xmlns:autn="http://schemas.autonomy.com/aci/">
<action>QUERY</action>
<response>SUCCESS</response>
<responsedata>
<autn:numhits>6</autn:numhits>
<autn:hit>
<autn:reference>http://something.what.com/index.php?title=DPM</autn:reference>
<autn:id>548166</autn:id>
<autn:section>0</autn:section>
<autn:weight>87.44</autn:weight>
<autn:links>Castlmania,POUCH</autn:links>
<autn:database>Postgres</autn:database>
<autn:title>A Pouch and Mail - Castlmania</autn:title>
<autn:content>
<DOCUMENT>
<DRETITLE>Castlmania Pouch and Mail - Castlmania</DRETITLE>
<DRECONTENT>A paragraph of sorts that would contain content</DRECONTENT>
</DOCUMENT>
</autn:content>
</autn:hit>
<autn:hit>...</autn:hit>
<autn:hit>...</autn:hit>
<autn:hit>...</autn:hit>
<autn:hit>...</autn:hit>
</autnresponse>
沒有運氣。 我正在使用此代碼開始:
XmlDocument xmlString = new XmlDocument();
xmlString.LoadXml(xmlUrl);
XmlElement root = xmlString.DocumentElement;
XmlNode GeneralInformationNode =
root.SelectSingleNode("//autnresponse/responsedata/autn:hit");
foreach (XmlNode node in GeneralInformationNode)
{
Console.Write("reference: "+node["autn:reference"]+" Title:"+node["DRETITLE"]+"<br />);
}
我想在每個autn:hit元素中打印DRETITLE和autn:reference元素。 我的方法甚至可行嗎?
我已經嘗試了好舊的Web像看幾個例子這無濟於事。
返回的錯誤是:
System.Xml.XPath.XpathEception {需要名稱空間管理器或XsltContext。 ...}
提前致謝。
更新:
在嘗試使用XmlNamespaceManager時,必須給它一個指向架構定義的網址,如下所示:
XmlNamespaceManager namespmng = new XmlNamespaceManager (xmlString.NameTable);
namespmng.AddNamespace("autn","http://someURL.com/XMLschema");
問題似乎是現在錯誤消失了,但是數據沒有顯示。 我應該提到我正在使用沒有互聯網連接的機器。 另一件事是該架構似乎不可用。 我猜XmlNamespaceManager一旦能夠連接到互聯網就可以正常工作嗎?
使用System.Xml.Linq
可能是這樣的:
var doc = XElement.Load(xmlUrl);
var ns = doc.GetNamespaceOfPrefix("autn");
foreach (var hit in doc.Descendants(ns + "hit"))
{
var reference = hit.Element(ns + "reference").Value;
var dretitle = hit.Descendants("DRETITLE").Single().Value;
WriteLine($"ref: {reference} title: {dretitle}");
}
首先,您得到的異常是因為尚未使用要解析的xml的XmlNamespaceManager
加載名稱空間。 像這樣:
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlString.NameTable);
if (root.Attributes["xmlns:autn"] != null)
{
uri = root.Attributes["xmlns:autn"].Value;
namespaceManager.AddNamespace("autn", uri);
}
其次,您想要做的是可能的。 我建議使用root.SelectNodes(<your xpath here>)
將返回可以循環通過的autn:hit節點的集合,而不是使用SelectSingleNode
,它將返回一個節點。 在其中,您可以向下鑽取到content / DOCUMENT / DRETITLE並使用XmlNode.Value
如果專門選擇文本)或在DRETITLE節點上選擇XmlNode.InnerText
來拉出DRETITLE節點的文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.