簡體   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