使用 Linq to xml 进行查询

发布于 2024-09-14 05:19:58 字数 907 浏览 1 评论 0原文

我对 Linq 相当陌生,我正在尝试编写一个简单的查询来返回 xml 文件中的错误消息。

<?xml version="1.0" encoding="utf-8"?>
<Error xmlns="urn:xxxxx">
            The following errors were detected:
            <Message>Internal Error</Message></Error>

以下内容有效并返回错误消息:

     Dim loaded As XDocument = XDocument.Parse(strReturn)
     Dim ns As XNamespace = "urn:xxxxx"
     Dim errors = From err In loaded.Descendants(ns + "Error") _
                                   Select err.Elements(ns + "Message").Value

但以下内容无效并且不返回任何结果:

Imports <xmlns="urn:xxxxx">
Dim loaded As XDocument = XDocument.Parse(strReturn)
Dim errors = From err In loaded.Descendants.<Error> _
                                 Select err.Elements.<Message>.Value

我只是想更好地理解 Linq 但有人可以告诉我为什么后者不起作用,因为它们不应该返回相同的结果?

提前致谢

I am Fairly new to Linq and I am trying to write a simple query to return the error messages within my xml file.

<?xml version="1.0" encoding="utf-8"?>
<Error xmlns="urn:xxxxx">
            The following errors were detected:
            <Message>Internal Error</Message></Error>

The following works and returns the error message:

     Dim loaded As XDocument = XDocument.Parse(strReturn)
     Dim ns As XNamespace = "urn:xxxxx"
     Dim errors = From err In loaded.Descendants(ns + "Error") _
                                   Select err.Elements(ns + "Message").Value

but the following does not and returns no results:

Imports <xmlns="urn:xxxxx">
Dim loaded As XDocument = XDocument.Parse(strReturn)
Dim errors = From err In loaded.Descendants.<Error> _
                                 Select err.Elements.<Message>.Value

I am just trying to get a better understand of Linq but can someone tell me why the later does not work as should they both not return the same result?

Thanks in advance

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

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

发布评论

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

评论(1

染火枫林 2024-09-21 05:19:58

编写 . 会调用 Elements 方法,因此当您调用 err.Elements. 时,您正在执行 err.Elements。 Elements("Message") 并获取 err 子级的子级,而不仅仅是其子级。只需删除对后代和元素的额外调用即可。如果您想要加载的后代而不仅仅是子级,则需要使用 ... 而不是 .

Dim errors = From err In loaded...<Error> _
             Select err.<Message>.Value

Writing .<Error> makes a call to the Elements method, so when you call err.Elements.<Message> you are doing err.Elements.Elements("Message") and getting the children of the children of err instead of just its children. Just remove the extra calls to Descendants and Elements. You will need to use ... instead of . if you want descendants of loaded instead of just children.

Dim errors = From err In loaded...<Error> _
             Select err.<Message>.Value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文