To use XDocument with XPath, you will need to reference the following namespace.
- using System.Xml
- using System.Xml.XPath
The former is useful to introduce XDocument, the later will add the Extension method to make it work well with the XPath. One of the method that we will introduce in this example is the
public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression);
Below shows how you query against the following data.
<?xml version="1.0" encoding="utf-8"?>
<Report Id="ID1" Type="Demo Report" Created="2011-01-01T01:01:01+11:00" Culture="en" xmlns="http://demo.com/2011/demo-schema">
<ReportInfo>
<Name>Demo Report</Name>
<CreatedBy>Unit Test</CreatedBy>
</ReportInfo>
</Report>
var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
You can also do with this (with help from XPath)
var document = XDocument.Load("fileName"); // Added missing endquote. It won't submit unless I type more.
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("emtpy", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/emtpy:Report/emtpy:ReportInfo/emtpy:Name", namespaceManager).Value;
本文介绍如何使用XDocument结合XPath查询XML文件。通过示例展示了如何加载XML文档,并使用XPathSelectElement方法选择节点,同时介绍了使用命名空间管理器处理命名空间的方法。
292

被折叠的 条评论
为什么被折叠?



