繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM