hWorld
hWorld

Reputation: 185

C#: Search value within an xml tag

I have a question as to how i can search an xml file and get the node that matches the text i provide. Ex:

<bookstore>
 <book>
  <title>The Autobiography of Benjamin Franklin</title>
  <author>
   <first-name>Benjamin</first-name>
   <last-name>Franklin</last-name>
  </author>
  <price>8.99</price>
  </book>
</bookstore>

I want to search for the node that has the text Benjamin and have the program store the XmlNode . How can i do this? Can anyone please provide sample code for this ex?

Thanks

Upvotes: 1

Views: 7022

Answers (4)

xling
xling

Reputation: 252

XPath

XmlDocument dom = new XmlDocument ( );

dom.LoadXml ( xml );


var nodes = dom.SelectNodes ( "//*[text()='Benjamin']" );

Upvotes: 0

LDAdams
LDAdams

Reputation: 682

Take a look at this: https://web.archive.org/web/20211020111721/https://www.4guysfromrolla.com/articles/062310-1.aspx

Linq makes searching in XML very easy.

Here is an example:

        XDocument doc = XDocument.Load("C:\\yourxml.xml");
        XElement element = 
            doc.Element("bookstore")
                .Descendants("book")
                .Where(a => a.Element("author")
                    .Element("first-name").Value.Equals("Benjamin"))
                    .First();

Upvotes: 7

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

LDAdams suggests LINQ to XML, which is a very good option. You can also use the XML DOM objects in .NET and use XPath queries to find the node in question. Either is an acceptable option. The benefit of LINQ to XML si it uses extension methods rather than XPath, making it easier for a non-XML savvy developer to get an answer. In addition, the knowledge at least partially applies to other LINQ derivatives.

Upvotes: 0

Hasan Fahim
Hasan Fahim

Reputation: 3885

Try this:

while (reader.Read())
  {
    switch (reader.NodeType)
    {
      case XmlNodeType.Element: 
        break;
      case XmlNodeType.Text:            
       if (reader.Value.Equals(wrd)) // string wrd equals Benjamin
           {

           }
           break;
    }

Upvotes: 1

Related Questions