如何在C#中解析嵌套的XML节点

时间:2016-07-22 18:44:05

标签: c# xml

我对C#很新,但似乎这应该是非常直接的。我正在尝试解析从Web Feed返回的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元素。我的做法是否可行?

我在this之类的旧网上试过看几个例子但没有用。

返回的错误是:

  

System.Xml.XPath.XpathEception {NameSpace Manager或XsltContext   需要。 ...}

提前致谢。

更新

在尝试使用XmlNamespaceManager时,必须为模式定义提供一个url,如下所示:

XmlNamespaceManager namespmng = new XmlNamespaceManager (xmlString.NameTable);
namespmng.AddNamespace("autn","http://someURL.com/XMLschema");

问题似乎是现在错误消失了,但数据没有显示。我应该提一下,我正在使用没有互联网连接的机器。另一件事是架构似乎不可用。我猜测XmlNamespaceManager能够连接到互联网吗?

2 个答案:

答案 0 :(得分:3)

使用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}");
}

答案 1 :(得分:2)

首先,您获得的例外情况是因为您尚未使用XmlNamespaceManager为您正在解析的xml加载命名空间。像这样:

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,它将返回一个节点。在其中,如果您专门选择文本或在DRETITLE节点上XmlNode.Value,您可以使用XmlNode.InnerText向下钻取内容/ DOCUMENT / DRETITLE并为DRETITLE节点提取文本。

相关问题