如何选择带有命名空间的XML节点

时间:2014-11-03 15:26:59

标签: c# xml xpath xmldocument

我需要获取第二个<Item>节点下的<Folder>个节点列表。如果我使用以下XML源代码和C#代码,则将FolderNode设置为正确的节点(第二个<Folder>节点),但将ItemsList设置为文件中每个<Item>的集合,包括第一文件夹节点。因此,ItemsList包含5个项而不是3个。

XML来源:

<?xml version="1.0" encoding="UTF-8"?>
<MMM xmlns="http://some.url.com/2.0">
    <Document>
        <open>1</open>
        <Folder>
            <name>Folder_1_Data</name>
            <Item>
                <description>Folder 1 Item 1</description>
            </Item>
            <Item>
                <description>Folder 1 Item 2</description>
            </Item>
        </Folder>
        <Folder>
            <name>Folder_2_Data</name>
            <Item>
                <description>Folder 2 Item A</description>
            </Item>
            <Item>
                <description>Folder 2 Item B</description>
            </Item>
            <Item>
                <description>Folder 2 Item C</description>
            </Item>
        </Folder>
    </Document>
</MMM>

C#代码:

    var doc = new XmlDocument();
    doc.Load("Import.xml");
    var nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("abc", "http://some.url.com/2.0");
    var xnlNodes = doc.SelectNodes("//abc:Document", nsmgr);
    var FolderNode = doc.SelectNodes("//abc:Folder", nsmgr).Item(1);

    var ItemsList = FolderNode.SelectNodes("//abc:Item", nsmgr);
    //Loop through each item in the 2nd folder node
    //and pull out the description of each item.

1 个答案:

答案 0 :(得分:1)

您只需添加一个前导.即表示XPath与当前FolderNode相关:

var ItemsList = FolderNode.SelectNodes(".//abc:Item", nsmgr);
                                      //^notice this dot

由于<Item>节点是<Folder>节点的直接子节点,您也可以这样做:

var ItemsList = FolderNode.SelectNodes("abc:Item", nsmgr);
                                      //without symbols at the beginning which..
                                      //^.. will return only direct children nodes

或者这样:

var ItemsList = FolderNode.SelectNodes("./abc:Item", nsmgr);
                                      //^using single slash which also return.. 
                                      //.. only direct children nodes