2017-08-13 44 views
0

你好我的朋友知道属性名称的节点我有一个这样的XML:使用XPath找到没有在C#

<?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> 

,如果我用这个XPath查询是OK:

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

和我会得到正确的答案:杰克·凯鲁亚克

但问题就在这里,当我没有属性的名字是这样的:

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

而且我不知道节点的第一个属性的名称是什么。

我怎样才能找到一个节点与xpath,而不知道任何节点的第一个属性名称? (我只是有用于过滤的节点属性值)

感谢

+3

你的意思是像'“//书[@ * = '小说'] //标题“'? – Andersson

+0

你应该发布你有问题的XML,而不是你找到答案的那个。 – Guy

+0

是的,那正是我想要的。谢谢。 –

回答

0

使用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(); 
     } 
    } 
} 
+0

谢谢,但我想找到一个像这样的xpath节点:// book ['Fiction'] //标题 –

+0

@Andersson找到了解决方案:“// book [@ * ='Fiction'] // title” –