Link to home
Start Free TrialLog in
Avatar of SuperGhosty
SuperGhosty

asked on

XPath Iterating through nodes with C#

I'm using C# and reading an XML document like the following (example):

<it>
    <abc>123</abc>
    <stuff>0</stuff>
    <jumbo>
        <big>false</big>
        <large>true</large>
    </jumbo>
</it>

I'm using the xPathNavigator and xPathNodeIterator to go through each node. The problem is I don't always know what nodes will be in the <it> node. So I need a way to iterate through the nodes and just add the node name and value to an array. I've almost got it however when I use the xPathNodeIterator and search all descendants it returns "falsetrue" for the <jumbo> node - apparently reading the value of this node concatenates the two child node values.

Is there a way around this? I want to iterate through each node and return just the node name and value without adding an element that has child elements.
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Can you post your code ? Saves me having to knock up my own sample ;o)
Avatar of SuperGhosty
SuperGhosty

ASKER

Yea I was at work when I posted so didn't have it available, but here you go, this is what I use to iterate through each element:

        private void Iterate(XPathNavigator xpNav)
        {
                XPathNodeIterator nodes = xpNav.Select("/it/prc/item");
                XPathNavigator nodesNavigator = nodes.Current;
                XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Element, false);

                while (nodes.MoveNext())
                {
                    if (!otherNodes.ContainsKey(nodes.Current.Name))
                    {
                        otherNodes.Add(nodes.Current.Name, nodes.Current.Value);
                    }
                }
        }
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Anything with text. And yes you're correct, for the example above I am getting one item being the sum of all the child nodes (what i dont want) and then the individual child nodes (what i do want).

I tried adding a check for child nodes using the following codes, however it doesn't seem to do anything - I get the same results:

        if (nodesText.Current.HasChildren) {
            //skip
        } else {
            //add to hashtable
        }