对 XLinq 帮助不大

发布于 2024-11-14 07:21:31 字数 583 浏览 2 评论 0原文

我有这个 XML:

<Test>
    <element>toto</element>
    <element>tata</element>
</Test>

如何获取节点“元素”?。我在网上看到我可以通过以下方式获取它们:

var elements = from element in xmlDoc.Descendants("element")
               select element;

但是“元素”是空的!

编辑 1: 我正在使用以下确切的 XML 加载 XDocument:

<Test xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
    <element>toto</element>
    <element>tata</element>
</Test>

I have this XML:

<Test>
    <element>toto</element>
    <element>tata</element>
</Test>

How I can get the nodes "element"?. I see on the web I can get them with:

var elements = from element in xmlDoc.Descendants("element")
               select element;

But "elements" is empty!

EDIT 1: I'm loading the XDocument with this exact XML:

<Test xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
    <element>toto</element>
    <element>tata</element>
</Test>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初吻给了烟 2024-11-21 07:21:31

好吧,这就是您的问题,您的名称必须使用适当的 XML 命名空间进行限定。

XNamespace ns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
var elements = xmlDoc.Descendants(ns + "element");

Ok well there's your problem, your names have to be qualified with the appropriate XML namespace.

XNamespace ns = "http://schemas.microsoft.com/ado/2007/08/dataservices";
var elements = xmlDoc.Descendants(ns + "element");
放血 2024-11-21 07:21:31

这可能是您创建 XDocument 对象的方式有问题。以下代码对我来说效果很好:

var doc = XDocument.Parse(@"
    <Test>
        <element>toto</element>
        <element>tata</element>
    </Test>");
var elements = doc.Descendants("element");
//prints "2"
Console.WriteLine(elements.Count());

It is probably a problem with how you are creating your XDocument object. The following code works fine for me:

var doc = XDocument.Parse(@"
    <Test>
        <element>toto</element>
        <element>tata</element>
    </Test>");
var elements = doc.Descendants("element");
//prints "2"
Console.WriteLine(elements.Count());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文