在C#中,使用System.Xml.XPath命名空间可以方便地处理XPath表达式
假设我们有以下XML文档:
Book 1 Author 1 Book 2 Author 2 Book 3 Author 3
现在,我们将使用C#和XPath表达式来查询此XML文档。
- 选择所有书籍的标题:
using System; using System.Xml; using System.Xml.XPath; class XPathExample { static void Main() { string xml = @""; 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 1 Author 1 Book 2 Author 2 Book 3 Author 3
输出:
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 = @""; 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 1 Author 1 Book 2 Author 2 Book 3 Author 3
输出:
Book with ID 2: Book 2 Author 2
这些示例展示了如何使用C#和XPath表达式查询XML文档。您可以根据需要修改这些示例以满足您的实际需求。