简体   繁体   中英

Using xpath to find a node without knowing attributes name in c#

Hello My Friends i have an xml like this:

<?xml version="1.0" encoding="utf-8" ?>
<books>    
  <book category="Fiction" >
     <author>Jack Kerouac</author>
     <title>On the Road</title>
 </book>

  <book category="IT" >
     <author>Stephen Walther</author>
     <title>ASP.NET Unleashed</title>
 </book>     
</books>

It is OK if i use this xpath query :

string query = "//book[@category='Fiction']//title";
XPathNodeIterator xPathIt = p_xPathNav.Select(query);

and I'll get the answer right : Jack Kerouac

But the problem is here,when i don't have attributes name like this:

string query = "//book['Fiction']//title";

And I don't know what is the name of the first attributes of nodes.

How can i find a node with xpath , without knowing first attribute name of any nodes? (i just have attribute value for filtering the nodes)

Thanks

Use xml linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement book = doc.Descendants("book").Where(x => x.Descendants().Select(y => (string)y == "Jack Kerouac").Any()).FirstOrDefault();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM