在C#中,使用System.Xml.XPath命名空間可以方便地處理XPath表達式
假設我們有以下XML文檔:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="1">
<title>Book 1</title>
<author>Author 1</author>
</book>
<book id="2">
<title>Book 2</title>
<author>Author 2</author>
</book>
<book id="3">
<title>Book 3</title>
<author>Author 3</author>
</book>
</books>
現在,我們將使用C#和XPath表達式來查詢此XML文檔。
using System;
using System.Xml;
using System.Xml.XPath;
class XPathExample
{
static void Main()
{
string xml = @"
<books>
<book id='1'>
<title>Book 1</title>
<author>Author 1</author>
</book>
<book id='2'>
<title>Book 2</title>
<author>Author 2</author>
</book>
<book id='3'>
<title>Book 3</title>
<author>Author 3</author>
</book>
</books>";
XPathDocument doc = new XPathDocument(xml);
XPathNavigator navigator = doc.CreateNavigator();
XPathExpression expr = navigator.Compile("//title");
XPathNodeIterator iterator = expr.Select();
Console.WriteLine("Book titles:");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Value);
}
}
}
輸出:
Book titles:
Book 1
Book 2
Book 3
using System;
using System.Xml;
using System.Xml.XPath;
class XPathExample
{
static void Main()
{
string xml = @"
<books>
<book id='1'>
<title>Book 1</title>
<author>Author 1</author>
</book>
<book id='2'>
<title>Book 2</title>
<author>Author 2</author>
</book>
<book id='3'>
<title>Book 3</title>
<author>Author 3</author>
</book>
</books>";
XPathDocument doc = new XPathDocument(xml);
XPathNavigator navigator = doc.CreateNavigator();
XPathExpression expr = navigator.Compile("//book[@id='2']");
XPathNodeIterator iterator = expr.Select();
Console.WriteLine("Book with ID 2:");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Value);
}
}
}
輸出:
Book with ID 2:
Book 2
Author 2
這些示例展示了如何使用C#和XPath表達式查詢XML文檔。您可以根據需要修改這些示例以滿足您的實際需求。