首頁 後端開發 XML/RSS教程 xml學習(6) 在c#Xpath實例

xml學習(6) 在c#Xpath實例

Feb 23, 2017 pm 02:37 PM

轉載:http://www.php.cn/

#在c#中,我們常常找,遍歷節點,這是我們可以用到XPath語法,XPath語法很簡單,但是強大夠用,XPath可以快速定位到Xml中的節點或屬性,它也是使用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的語法:

1. XPath中的符號

##..@xx[…]//dog[@color='white']所有price字節點值小於100的dog節點//dog[1]##| ##*

符號

##說明

#範例

#範例說明

#/

表示從根節點開始選擇

/pets

選擇根節點pets

表示節點與子節點之間的間隔符號

/pets/dog

選擇pets節點下的dog節點

//xx

表示從整個xml文件中尋找,而不考慮目前節點位置

//price

#選擇文件中所有的price節點

#.

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

/pets/.

選擇pets節點

#雙點,表示選擇父節點

/pets/dog[0 ]/..

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

表示選擇屬性

#//dog/@color

表示選擇所有dog節點的color屬性集合

#中括號表示選擇條件,括號內為條件

所有color為white的dog節點

//dog[/price<100]

中括號內數字為節點索引,類似c#等語言中的陣列,陣列下標是從1開始的

第1個dog節點

//dog[ last()]

最後一個dog節點,last()是xPath內建函數

單一垂直槓表示合併節點結合

#//dog[@color='white'] | //cat[ @color='white']

color屬性為white的dog節點和color屬性為white的cat節點

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

//dog/*
表示dog節點的所有子節點###################//dog/@*########## ##表示dog節點的所有屬性節點################

 


2. XPath數學運算子

+ 加號表示加上

- 表示數字相減

* 表示乘以

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

mod 表示取餘

 

3. XPath邏輯運算子

= 等於,相當於c#中的==

!= 不等於

> 大於

>= 大於等於

< 小於

<= 小於等於

#and 並且與關係

or 或或關係

 

 

4. XPath Axes 從字面上翻譯這個是XPath軸的意思,但根據我的理解這個翻譯成XPath節點關係運算關鍵字更合適,就是一組關鍵字加上::雙冒號表示和當前節點有關係的一個或者一組節點.

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

具體說明如下:

#範例ancestor目前節點的父祖節點ancestor::pig##都相當於@weight,attribute::和@是等價的選擇名字不是price的子節點有屬性的子孫節點 # followingXml文件中當前節點之後的所有節點#following::*##following-sibling「目前節點的同父弟弟節點following-sibling: :precedingXml文件中目前節點之前的所有節點
##關鍵字

說明

#範例

##範例說明

##ancestor:: pig
目前節點的祖先節點中的pig節點

#ancestor-or-self

目前節點以及其父祖節點

 

##attribute

目前節點的所有屬性

#attribute::weight

#child

目前節點的所有位元組點

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

descendant

子孫節點

descendant::*[@*]

#descendant-or-self

子孫節點以及當前節點

descendant-or-self::*

 

 

###preceding::*######### ###############namespace################################################選取目前節點的所有命名空間節點############namespace::*########## ##############parent# ###########目前節點的父節點############parent::############相當於雙點..# #################preceding-sibling#############目前節點之後的同父兄節點########## #preceding-sibling::*######### ################self###########目前節點##################################################### ########self::*############相當於單點.###############


5. 常用的XPath函数介绍:

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

position() 表示节点的序号例如 //cat[position() = 2] 表示取序号为2的dog节点

last() 表示取最后一个节点 //cat[last()]

name() 表示当前节点名字 /pets/*[name() != 'pig'] 表示/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();
}
}
}
登入後複製

 以上就是xml学习(6) 在c#Xpath实例的内容,更多相关内容请关注PHP中文网(www.php.cn)! 


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

使用 C# 的活動目錄 使用 C# 的活動目錄 Sep 03, 2024 pm 03:33 PM

使用 C# 的 Active Directory 指南。在這裡,我們討論 Active Directory 在 C# 中的介紹和工作原理以及語法和範例。

C# 中的隨機數產生器 C# 中的隨機數產生器 Sep 03, 2024 pm 03:34 PM

C# 隨機數產生器指南。在這裡,我們討論隨機數產生器的工作原理、偽隨機數和安全數的概念。

C# 資料網格視圖 C# 資料網格視圖 Sep 03, 2024 pm 03:32 PM

C# 資料網格視圖指南。在這裡,我們討論如何從 SQL 資料庫或 Excel 檔案載入和匯出資料網格視圖的範例。

您如何在PHP中解析和處理HTML/XML? 您如何在PHP中解析和處理HTML/XML? Feb 07, 2025 am 11:57 AM

本教程演示瞭如何使用PHP有效地處理XML文檔。 XML(可擴展的標記語言)是一種用於人類可讀性和機器解析的多功能文本標記語言。它通常用於數據存儲

C# 中的模式 C# 中的模式 Sep 03, 2024 pm 03:33 PM

C# 模式指南。在這裡,我們討論 C# 中模式的介紹和前 3 種類型,以及其範例和程式碼實作。

C# 中的階乘 C# 中的階乘 Sep 03, 2024 pm 03:34 PM

C# 階乘指南。這裡我們討論 C# 中階乘的介紹以及不同的範例和程式碼實作。

C# 中的質數 C# 中的質數 Sep 03, 2024 pm 03:35 PM

C# 質數指南。這裡我們討論c#中素數的介紹和範例以及程式碼實作。

c#多線程和異步的區別 c#多線程和異步的區別 Apr 03, 2025 pm 02:57 PM

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。

See all articles