使用 XDocument 按属性查找元素
这个查询似乎是有效的,但我有 0 个结果。
IEnumerable<XElement> users =
(from el in XMLDoc.Elements("Users")
where (string)el.Attribute("GUID") == userGUID.ToString()
select el);
我的 XML 如下:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Users>
<User GUID="68327fe2-d6f0-403b-a7b6-51860fbf0b2f">
<Key ID="F7000012ECEAD101">
...
</Key>
</User>
</Users>
您有任何线索可以阐明这一点吗?
This query seems to be valid, but I have 0 results.
IEnumerable<XElement> users =
(from el in XMLDoc.Elements("Users")
where (string)el.Attribute("GUID") == userGUID.ToString()
select el);
My XML is as follows:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Users>
<User GUID="68327fe2-d6f0-403b-a7b6-51860fbf0b2f">
<Key ID="F7000012ECEAD101">
...
</Key>
</User>
</Users>
Do you have any clues to shed some light onto this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将第二行中的
Users
更改为User
。像这样:我假设 XMLDoc 是一个 XDocument,而不是根元素本身。
change
Users
in the 2nd line toUser
. Like this:I'm assuming XMLDoc is an XDocument, and not the root element itself.
嗯,Users 元素没有 GUID 属性。两个建议选项:
XDocument.Root.Elements("User")
Descendants("User")
查找所有User 元素。我暂时坚持前者。这给了我们:
现在,我们仍然可以进一步整理它。首先,让我们转换为
Guid
而不是string
:但是,这里没有太多理由使用查询表达式......您所应用的只是一个谓词。让我们直接使用
Where
方法:当然,如何布局取决于您:) 如果行较长,您可能可以将所有内容对齐在较长的第一行下:
现在,最后 -如果 User 元素没有 GUID 属性怎么办?目前,此代码将引发异常。这可能正是您想要的——也可能不是。如果不是,您可以通过转换为
Nullable
又名Guid?
来使其忽略此类内容:Well, the Users elements don't have GUID attributes. Two suggested options:
XDocument.Root.Elements("User")
Descendants("User")
to find all User elements.I'll stick with the former for the moment. That gives us:
Now, we can still tidy this up further. Firstly, let's cast to
Guid
instead ofstring
:However there's not a lot of reason to use a query expression here... all you're applying is a single predicate. Let's just use the
Where
method directly:How you lay it out is up to you, of course :) With a longer line, you can probably align everything up under a longer first line:
Now, finally - what about if the User element doesn't have a GUID attribute? Currently, this code will throw an exception. That may be exactly what you want - or it may not. If it's not, you can make it ignore such things by casting to
Nullable<Guid>
akaGuid?
instead: