【问题标题】:How to get a collection of all direct child nodes of a node?如何获取一个节点的所有直接子节点的集合?
【发布时间】:2021-12-26 13:30:28
【问题描述】:

在 C# 中,您可以使用 SelectNodes() API 调用并传递 XPath 来查询 XmlNode 以查找其子节点。

获取直接子节点集合的XPath是什么?

例如,

<actions>
    <if operation="A"> 
       <if operation="B">
            <store>some value</store>
            <if operation="C"> .... </if>
       </if>
    </if>
    <store>value</store>
</actions>

在上面的例子中,我需要得到&lt;actions&gt; 的直接子节点:&lt;if operation="A"&gt;&lt;store&gt;。 由于 XML 的递归特性,每个if 节点都可以保存另一个if 的列表。

我试过actionNode.SelectNodes("child::*"),但它给了我&lt;action&gt;下面的整个节点树(假设actionNode指向&lt;action&gt; XML)。

【问题讨论】:

  • 如果您想获取所有子元素,只需使用myXmlNode.ChildNodes 集合。如果您只想要一些子节点或子子节点,SelectNodes() 很有用。在这种情况下,您可以通过 xpath 声明您的选择器表达式。

标签: c# xml-parsing


【解决方案1】:

节点直接子节点可通过节点的ChildNodes 属性获得。看看如何使用它。

[TestMethod]
public void MyTestMethod3()
{
    var xml = new XmlDocument();
    xml.LoadXml(
        @"<actions>
            <if operation=""A""> 
                <if operation=""B"">
                    <store>some value</store>
                    <if operation=""C""> .... </if>
                </if>
            </if>
            <store>value</store>
            </actions>
    ");

    var actionsNode = xml.SelectSingleNode("/actions");

    // all direct child nodes are available through node.ChildNodes property
    var directChildren = actionsNode.ChildNodes;

    // here is the proof:
    CollectionAssert.AreEquivalent(
        new string[] { "if", "store" }, 
        directChildren.Cast<XmlNode>().Select(i => i.Name).ToArray());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2018-08-12
    相关资源
    最近更新 更多