繁体   English   中英

当两个子节点都必须存在时,如何使用XPath从XML文件中提取子节点?

[英]How do I extract child nodes from XML file using XPath when both child nodes must exist?

我正在尝试从xml文档中提取某些值。 在下面的示例中,我想将存储在“ c”和“ d”节点中的值存储在列表中,但仅在“ b”节点同时包含“ c”和“ d”的情况下。 到目前为止,我拥有的代码循环遍历所有“ b”节点,但是我不确定在while循环中放入什么,或者这是否是最佳方法。

XmlDocument attrsXML = new XmlDocument();
attrsXML.LoadXml(dbReader["SampleXml"].ToString());

XPathNavigator nav = attrsXML.CreateNavigator();

XPathNodeIterator attribNodes = nav.Select("/a/b");

while (attribNodes.MoveNext())
{
    // What do I need to put here in order to extract the 'c' and 'd' nodes?
    // Any other nodes can be ignored (such as 'e' above). I am only interested
    // when 'b' contains both 'c' AND 'd'.
}

从数据库加载的“ SampleXml”在哪里:

<a>
    <b>
        <c>Extract this</c>
        <d>And this</d>
        <e>not this</e>
    </b>
    <b>
        <c>not this</c>
        <e>not this</e>
    </b>
    <b>
        <c>Extract this</c>
        <d>And this</d>
    </b>
</a>

任何帮助表示赞赏。

您可以使用以下代码:

XmlDocument attrsXML = new XmlDocument();
attrsXML.LoadXml(dbReader["SampleXml"].ToString());


XmlNodeList nodeList = attrsXML.SelectNodes("/a/b[c and d]");

foreach (XmlNode xmlNode in nodeList)
{
  string cText = xmlNode.SelectSingleNode("c").InnerText;
  string dText = xmlNode.SelectSingleNode("d").InnerText;
}

XPath“ / a / b [c和d]”返回所有包含c和d元素的b个元素作为子元素,这意味着您不需要在循环内手动检查它。

我是这样解决的:

while (attribNodes.MoveNext())
{
    string cText = String.Empty;
    string dText = String.Empty;

    XPathNavigator nav2 = attribNodes.Current;

    var cNode = nav2.SelectSingleNode("c");

    if (cNode != null)
    {
        cText = nameNode.ToString();

        var dNode = nav2.SelectSingleNode("d");
        if (dNode != null)
        {
            dText = dNode.ToString();
        }
    }

    if (dText != String.Empty && cText != String.Empty)
    {
        // Problem solved
    }
}

欢迎任何更好的解决方案,因为它看起来不太优雅。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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