首頁  >  文章  >  後端開發  >  XPath語法: 在C#中使用XPath範例的具體程式碼介紹

XPath語法: 在C#中使用XPath範例的具體程式碼介紹

黄舟
黄舟原創
2017-03-09 16:55:101706瀏覽

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