本主题介绍一些扩展方法,通过这些扩展方法可以使用 XPath 查询 XML 树。 有关使用这些扩展方法的详细信息,请参见 System.Xml.XPath.Extensions。
除非有很特别的理由(例如大量使用旧代码)需要使用 XPath 进行查询,否则不建议将 XPath 用于 LINQ to XML。 XPath 查询的执行性能比 LINQ to XML 查询低。
示例
下面的示例创建一个小型 XML 树,并使用 XPathSelectElements 选择一组元素。
XElement root = new XElement("Root",
new XElement("Child1", 1),
new XElement("Child1", 2),
new XElement("Child1", 3),
new XElement("Child2", 4),
new XElement("Child2", 5),
new XElement("Child2", 6)
);
IEnumerable<XElement> list = root.XPathSelectElements("./Child2");
foreach (XElement el in list)
Console.WriteLine(el);
Dim root As XElement = _
<Root>
<Child1>1</Child1>
<Child1>2</Child1>
<Child1>3</Child1>
<Child2>4</Child2>
<Child2>5</Child2>
<Child2>6</Child2>
</Root>
Dim list As IEnumerable(Of XElement) = root.XPathSelectElements("./Child2")
For Each el As XElement In list
Console.WriteLine(el)
Next
此示例产生以下输出:
<Child2>4</Child2>
<Child2>5</Child2>
<Child2>6</Child2>