阅读量:58
在C#中,使用System.Xml.XPath命名空间可以执行XPath查询。对于复杂的XPath查询,可以使用通配符(*)和谓词(例如@attribute='value')来筛选元素和属性。
以下是一个C#示例,展示了如何使用XPath查询一个包含多个元素的XML文档:
using System;
using System.Xml;
class Program
{
static void Main()
{
string xml = @"
<title>Book 1</title>
Author 1
<title>Book 2</title>
Author 2
<title>Book 3</title>
Author 3
";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string xpathQuery = "//book[@id='2']"; // 查询id属性值为'2'的book元素
XmlNodeList nodes = doc.SelectNodes(xpathQuery);
if (nodes.Count > 0)
{
Console.WriteLine("Found a book with id='2'");
}
else
{
Console.WriteLine("No book found with id='2'");
}
}
}
在这个示例中,我们使用XPath查询`//book[@id=’