如何在 XDocument 中使用 XPath? [英] how to use XPath with XDocument?

查看:41
本文介绍了如何在 XDocument 中使用 XPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个类似的问题,但似乎解决方案在我的情况下不起作用:XDocument、XPath 和命名空间的奇怪之处

There is a similar question, but it seems that the solution didn't work out in my case: Weirdness with XDocument, XPath and namespaces

这是我正在使用的 XML:

Here is the XML I am working with:

<?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>

下面是我认为它应该可以工作的代码,但它没有......

And below is the code that I thought it should be working but it didn't...

XDocument xdoc = XDocument.Load(@"C:SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace(String.Empty, "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/Report/ReportInfo/Name", xnm) == null);

有人有什么想法吗?谢谢.

Does anyone have any ideas? Thanks.

推荐答案

如果你有 XDocument,那么使用 LINQ-to-XML 会更容易:

If you have XDocument it is easier to use LINQ-to-XML:

var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;

如果您确定 XPath 是您需要的唯一解决方案:

If you are sure that XPath is the only solution you need:

using System.Xml.XPath;

var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;

这篇关于如何在 XDocument 中使用 XPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆