阅读量:0
在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
- 根据书籍ID选择书籍:
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文档。您可以根据需要修改这些示例以满足您的实际需求。