开发者

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>Benj开发者_开发百科amin</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


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();


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;
    }


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.


XPath

XmlDocument dom = new XmlDocument ( );

dom.LoadXml ( xml );


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜