使用 Linq to xml 进行查询
我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编写
.
会调用 Elements 方法,因此当您调用err.Elements.
时,您正在执行err.Elements。 Elements("Message")
并获取 err 子级的子级,而不仅仅是其子级。只需删除对后代和元素的额外调用即可。如果您想要加载的后代而不仅仅是子级,则需要使用...
而不是.
。Writing
.<Error>
makes a call to the Elements method, so when you callerr.Elements.<Message>
you are doingerr.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.