Harry Boy
Harry Boy

Reputation: 4745

Search an XmlNodeList for a specific string

Is there a way I can reduce the foreach code below so I don't have to use a foreach loop to iterate over the xml nodes?

I just want to look and see if an item is present in the xml file

XmlDocument doc = new XmlDocument();
doc.Load("MyList.xml");

XmlNodeList list = doc.SelectNodes("/MyList/item");
foreach( XmlNode item in list)
{
    string name = item.InnerText;
    if(name == "blah blah")
    {
       //do something
    }
}

The above works but I just want a smaller cooler way of doing it :)

Upvotes: 0

Views: 8362

Answers (2)

JLRishe
JLRishe

Reputation: 101700

If all you want to do is check whether a certain node exists, use SelectSingleNode with a filtered XPath:

XmlNode node = doc.SelectSingleNode("/MyList/item[. = 'blah blah']");
if (node != null)
{
    // do something
}

One issue here is that if the value you want to match on is a dynamic value, you should not build up the XPath by concatenating strings together. That would create an invalid XPath.

In that case, you can either use LINQ on an XmlNodeList:

var found = doc.SelectSingleNode("/MyList/item")
               .Cast<XmlNode>()
               .Any(n => n.InnerText == "blah blah");

or go ahead and use LINQ-to-XML:

XDocument doc = XDocument.Load("MyList.xml");

bool itemFound = doc.Element("MyList")
                   .Elements("item")
                   .Any(e => (string) e == "blah blah");

Upvotes: 2

har07
har07

Reputation: 89295

You can filter element by inner text directly in the XPath expression like so :

XmlNodeList list = doc.SelectNodes("/MyList/item[.='blah blah']");

Upvotes: 2

Related Questions