搜尋
首頁後端開發XML/RSS教程XPath語法: 在C#中使用XPath範例的具體程式碼介紹

XPath可以快速定位到Xml中的節點或屬性。 XPath語法很簡單,但是強大夠用,它也是使用xslt的基礎知識。

範例Xml:


<?xml version="1.0" encoding="utf-8" ?>
<pets>
  <cat color="black" weight="10">
    <price>100</price>
    <desc>this is a black cat</desc>
  </cat>
  <cat color="white" weight="9">
    <price>80</price>
    <desc>this is a white cat</desc>
  </cat>
  <cat color="yellow" weight="15">
    <price>80</price>
    <desc>this is a yellow cat</desc>
  </cat>


  <dog color="black" weight="10">
    <price>100</price>
    <desc>this is a black dog</desc>
  </dog>
  <dog color="white" weight="9">
    <price>80</price>
    <desc>this is a white dog</desc>
  </dog>
  <dog color="yellow" weight="15">
    <price>80</price>
    <desc>this is a yellow dog</desc>
  </dog>
</pets>



XPath的語法:

符號

表示選擇屬性屬性集合//dog[/price

,數組下標是從1內建函數的




2. XPath數學運算子

+

p

表示除以,這裡數學上的除號/已經被用作節點之間分隔符了

mod

表示取餘

3. XPath邏輯運算子

3. XPath邏輯運算子

= c#中的==!=

不等於>

大於>=

大於等於

等於 並且與關係

or 或或關係

4.

XPath Axes

從字面翻譯這個是XPath4. XPath Axes

從字面翻譯這個是XPath的意思,但根據我的關係理解這個關鍵字群組關鍵字加上::雙冒號表示和目前節點有關係的一個或一組節點.


使用語法:axisname::nodetest[predicate] 即軸名字::節點名字[取節點條件]

具體說明如下:



說明




範例說明



/


表示從根節點開始選擇



/pets s



表示節點和子節點之間的間隔符



/pets/dog


/pets/dog

節點下的
dog

節點


//xx





//price



選擇文件中所有的price節點


price

節點



單一英文半角句點表示選擇目前節點


/pets/.



選擇pets

..



雙點,表示選擇父節點



/pets/dog[0]/..

/pets/dog[0]/..

表示pets節點,也就是第一個dog節點的父節點







//dog/@color

//dog/@color


color

[…]



//dog[@color ='white']



所有

color

white


所有price字節點值小於100dog節點


號。
c#

等語言中的數組
開始的

//dog[1]


1dog節點



最後一個
dog

節點,

last()

xPath


單豎槓表示合併節點結合



//dog[@color='white'


color
屬性為

white
dog

節點和color屬性為white節點和color屬性為white

*


星號表示任何名字的節點或屬性



//dog/*




//dog /@*


表示
dog

節點的所有屬性節點


ancestorattributeattribute::選取目前節點的所有命名空間節點 



範例



範例說明



ancestor


ancestor



ancestor


🎜🎜🎜ancestor🎜🎜🎜

目前節點的父祖節點



ancestor::pig

pig
節點


ancestor-or-self



ancestor::pig



 


attribute


目前節點的所有屬性



attribute::weight


attribute::weight
@weight

@ 是等價的



child



child: :*[name()!='price']

選名字不是price的子節點



子孫節點



descendant::*[@*]



有屬性的子孫節點


or-self



子孫節點以及當前節點


descendant-or-self::*



 


Xml

文件中當前節點之後的所有節點



following::*



following-sibling



當前節點的同父弟弟節點



following-sibling::




preceding


Xml
文件中目前節點之前的所有節點


preceding::*



namespace



namespace::*



 



 


 


 


目前節點的父節點



parent::



preceding-sibling


🎜🎜

當前節點之後的同父兄節點



 



self


當前節點



相當於單點

.






5. 常用的XPath函数介绍:

在XPath表达式中常用的函数有下面两个:

position() 表示节点的序号例如 //cat[position() = 2] 表示取序号为2的dog节点
last() 表示取最后一个节点 //cat[last()] 
name() 表示当前节点名字 /pets/*[name() != &#39;pig&#39;] 表示/pets下名字不是pig的子节点


XPath的函数还有很多,包括字符串函数,数字函数和时间函数等,具体可以参考w3的网站。

以上是XPath的语法,下面我们看下如何在.Net中使用XPath

在.Net中可以通过XPathDocument或者XmlDocument类使用XPath。XPathDocument是只读的方式定位Xml节点或者属性文本等,而XmlDocument则是可读写的。

如下代码示例展示了如何使用XPathDocument和XmlDocument


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

namespace UseXPathDotNet
{
    class Program
    {
        static void Main(string[] args)
        {
            UseXPathWithXPathDocument();

            UseXPathWithXmlDocument();

            Console.Read();
        }

        static void UseXPathWithXmlDocument()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("http://www.cnblogs.com/yukaizhao/rss");
            //使用xPath选择需要的节点
            XmlNodeList nodes = doc.SelectNodes("/rss/channel/item[position()<=10]");
            foreach (XmlNode item in nodes)
            {
                string title = item.SelectSingleNode("title").InnerText;
                string url = item.SelectSingleNode("link").InnerText;
                Console.WriteLine("{0} = {1}", title, url);
            }
        }

        static void UseXPathWithXPathDocument()
        {
            XPathDocument doc = new XPathDocument("http://www.cnblogs.com/yukaizhao/rss");
            XPathNavigator xPathNav = doc.CreateNavigator();
            //使用xPath取rss中最新的10条随笔
            XPathNodeIterator nodeIterator = xPathNav.Select("/rss/channel/item[position()<=10]");
            while (nodeIterator.MoveNext())
            {
                XPathNavigator itemNav = nodeIterator.Current;
                string title = itemNav.SelectSingleNode("title").Value;
                string url = itemNav.SelectSingleNode("link").Value;
                Console.WriteLine("{0} = {1}",title,url);
            }

        }
    }
}


XPath使用示例,请看下面的代码注释 


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

namespace UseXPath1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<pets>
  <cat color=""black"" weight=""10"" count=""4"">
    <price>100</price>
    <desc>this is a black cat</desc>
  </cat>
  <cat color=""white"" weight=""9"" count=""5"">
    <price>80</price>
    <desc>this is a white cat</desc>
  </cat>
  <cat color=""yellow"" weight=""15"" count=""1"">
    <price>110</price>
    <desc>this is a yellow cat</desc>
  </cat>


  <dog color=""black"" weight=""10"" count=""7"">
    <price>114</price>
    <desc>this is a black dog</desc>
  </dog>
  <dog color=""white"" weight=""9"" count=""4"">
    <price>80</price>
    <desc>this is a white dog</desc>
  </dog>
  <dog color=""yellow"" weight=""15"" count=""15"">
    <price>80</price>
    <desc>this is a yellow dog</desc>
  </dog>

    <pig color=""white"" weight=""100"" count=""2"">
    <price>8000</price>
    <desc>this is a white pig</desc>    
    </pig>
</pets>";

            using (StringReader rdr = new StringReader(xml))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(rdr);

                //取所有pets节点下的dog字节点
                XmlNodeList nodeListAllDog = doc.SelectNodes("/pets/dog");

                //所有的price节点
                XmlNodeList allPriceNodes = doc.SelectNodes("//price");

                //取最后一个price节点
                XmlNode lastPriceNode = doc.SelectSingleNode("//price[last()]");

                //用双点号取price节点的父节点
                XmlNode lastPriceParentNode = lastPriceNode.SelectSingleNode("..");

                //选择weight*count=40的所有动物,使用通配符*
                XmlNodeList nodeList = doc.SelectNodes("/pets/*[@weight*@count=40]");

                //选择除了pig之外的所有动物,使用name()函数返回节点名字
                XmlNodeList animalsExceptPigNodes = doc.SelectNodes("/pets/*[name() != &#39;pig&#39;]");
               

                //选择价格大于100而不是pig的动物
                XmlNodeList priceGreaterThan100s = doc.SelectNodes("/pets/*[price p @weight >10 and name() != &#39;pig&#39;]");
                foreach (XmlNode item in priceGreaterThan100s)
                {
                    Console.WriteLine(item.OuterXml);
                }

                //选择第二个dog节点
                XmlNode theSecondDogNode = doc.SelectSingleNode("//dog[position() = 2]");

                //使用xpath ,axes 的 parent 取父节点
                XmlNode parentNode = theSecondDogNode.SelectSingleNode("parent::*");

                //使用xPath选择第二个dog节点前面的所有dog节点
                XmlNodeList dogPresibling = theSecondDogNode.SelectNodes("preceding::dog");

                //取文档的所有子孙节点price
                XmlNodeList childrenNodes = doc.SelectNodes("descendant::price");
            }

            Console.Read();
        }
    }
}



以上是XPath語法: 在C#中使用XPath範例的具體程式碼介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何解析和利用基於XML的RSS提要如何解析和利用基於XML的RSS提要Apr 16, 2025 am 12:05 AM

RSSFEEDSUSEXMLTOSYNDICATECONTENT; PARSINGTHEMINVOLVESLOADINGINGINGINGINSSTRUCTURE,andExtractingData.ApplicationsIncludeBuildBuildingNewSagGregatorSaterNewSagGregatorSator andTrackingPodcastepodcastepisodes。

RSS文檔:他們如何提供您喜歡的內容RSS文檔:他們如何提供您喜歡的內容Apr 15, 2025 am 12:01 AM

RSS文檔的工作原理是通過XML文件發佈內容更新,用戶通過RSS閱讀器訂閱並接收通知。 1.內容髮布者創建並更新RSS文檔。 2.RSS閱讀器定期訪問並解析XML文件。 3.用戶瀏覽和閱讀更新內容。使用示例:訂閱TechCrunch的RSS源,只需複制鏈接到RSS閱讀器中即可。

用XML建造供稿:RSS的動手指南用XML建造供稿:RSS的動手指南Apr 14, 2025 am 12:17 AM

使用XML構建RSSfeed的步驟如下:1.創建根元素並設置版本;2.添加channel元素及其基本信息;3.添加條目(item)元素,包括標題、鏈接和描述;4.轉換XML結構為字符串並輸出。通過這些步驟,你可以從零開始創建一個有效的RSSfeed,並通過添加額外的元素如發布日期和作者信息來增強其功能。

創建RSS文檔:逐步教程創建RSS文檔:逐步教程Apr 13, 2025 am 12:10 AM

創建RSS文檔的步驟如下:1.使用XML格式編寫,根元素為,包含元素。 2.在內添加、、等元素描述頻道信息。 3.添加元素,每個代表一個內容條目,包含、、、等。 4.可選地添加和元素,豐富內容。 5.確保XML格式正確,使用在線工具驗證,優化性能並保持內容更新。

XML在RSS中的作用:聯合內容的基礎XML在RSS中的作用:聯合內容的基礎Apr 12, 2025 am 12:17 AM

XML在RSS中的核心作用是提供一種標準化和靈活的數據格式。 1.XML的結構和標記語言特性使其適合數據交換和存儲。 2.RSS利用XML創建標準化格式,方便內容共享。 3.XML在RSS中的應用包括定義feed內容的元素,如標題和發布日期。 4.優勢包括標準化和可擴展性,挑戰包括文件冗長和嚴格語法要求。 5.最佳實踐包括驗證XML有效性、保持簡潔、使用CDATA和定期更新。

從XML到可讀的內容:揭開RSS feed的神秘面紗從XML到可讀的內容:揭開RSS feed的神秘面紗Apr 11, 2025 am 12:03 AM

rssfeedsarexmldocuments usedforcontentAggregation and distribution.totransformthemintoreadableContent:1)parsethethexmlusinglibrarieslibrariesliblarieslikeparserinparserinpython.2)andledifferentifferentrssssssssssssssssssssssssssssssssssssssssssssssersions andpotentionparsingrorS.3)

是否有基於JSON的RSS替代方案?是否有基於JSON的RSS替代方案?Apr 10, 2025 am 09:31 AM

JSONFeed是一種基於JSON的RSS替代方案,其優勢在於簡潔性和易用性。 1)JSONFeed使用JSON格式,易於生成和解析。 2)它支持動態生成,適用於現代Web開發。 3)使用JSONFeed可以提升內容管理效率和用戶體驗。

RSS文檔工具:構建,驗證和發布提要RSS文檔工具:構建,驗證和發布提要Apr 09, 2025 am 12:10 AM

如何構建、驗證和發布RSSfeeds? 1.構建:使用Python腳本生成RSSfeed,包含標題、鏈接、描述和發布日期。 2.驗證:使用FeedValidator.org或Python腳本檢查RSSfeed是否符合RSS2.0標準。 3.發布:將RSS文件上傳到服務器,或使用Flask動態生成並發布RSSfeed。通過這些步驟,你可以有效管理和分享內容。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),