繁体   English   中英

使用xpath查找节点而不知道c#中的属性名称

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

您好我的朋友们,我有这样的xml:

<?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查询,也可以:

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

我会正确回答: Jack Kerouac

但是问题出在这里,当我没有这样的属性名称时:

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

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

如何在不知道任何节点的第一个属性名称的情况下使用xpath查找节点? (我只是具有用于过滤节点的属性值)

谢谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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