user2874611
user2874611

Reputation: 11

How to skip nodes in an XMLDocument in C#

Say I have an XML document like this

<xml>
     <food>
            <banana>this is a banana</banana>
            <apple>this is an apple</apple>
            <grape>this is a grape</grape>
     </food>
     <food>
            <cake>this is cake</cake>
            <soda>this is soda</soda>
            <cookie>this is a cookie</cookie>
     </food>
</xml>

How would I skip to the second node of <food> to get the food from in there using an XMLDocument in C#? Any advice is appreciated!

Upvotes: 0

Views: 2435

Answers (2)

Bentoy13
Bentoy13

Reputation: 4974

You can use Enumerable.Skip (from the idea of @JeroenvanLangen in comments) but it needs a little trick:

XmlNodeList xnlNodes = Doc.SelectNodes("/food");
foreach(XmlNode node in xnlNodes.Cast<XmlNode>().Skip(1))
{
    //do sth
}

The cast trick is needed because XmlNodeList implements the interface IEnumerable but is not a IEnumerable<XmlNode>.

Upvotes: 0

dcp
dcp

Reputation: 55458

XmlDocument xdcDocument = new XmlDocument();

xdcDocument.LoadXml(<xml string>);

XmlElement xelRoot = xdcDocument.DocumentElement;
XmlNodeList xnlNodes = xelRoot.SelectNodes("/food");

bool first = true;
foreach(XmlNode xndNode in xnlNodes)
{
    if (first) {
        first = false;
        continue;
    }
    // process the second node here
}

Upvotes: 1

Related Questions