1

I need to get the list of <Item> nodes under the 2nd <Folder> node. If I use the following XML source and C# code, FolderNode is set to the correct node (2nd <Folder> node) but ItemsList gets set to a collection of every <Item> in the file, including the items in the 1st folder node. So, ItemsList contains 5 items instead of 3.

XML Source:

<?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# Code:

    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 Answer 1

1

You simply need to add a leading . to indicate that the XPath is relative to current FolderNode :

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

Since <Item> nodes are direct child of <Folder> node, you can also do this way :

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

or this way :

var ItemsList = FolderNode.SelectNodes("./abc:Item", nsmgr);
                                      //^using single slash which also return.. 
                                      //.. only direct children nodes
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.