需要有关 XElement 查询的帮助
此查询未按我的预期工作。有人看到问题了吗?
我试图通过名称获取元素,但它没有返回任何内容。以下是我需要帮助的函数的特定部分:
更新
解决方案是使用 XName 而不是字符串。就像这样:
var matchingElements = elements.Where(e => e.Name.Equals(XName.Get(name)));
This query isn't working as I'm expecting it to. Anyone see the problem?
I'm trying to get an element by it's name, but it's not returning anything. Here is the specific part of the function I need some help with:
Update
The solution was to use an XName instead of a string. Like so:
var matchingElements = elements.Where(e => e.Name.Equals(XName.Get(name)));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将您的行更改为:
LocalName
部分是重要的部分,否则您将比较XName
与string
的相等性。请记住,XML 支持“前缀:元素名称”样式的名称。在该示例中,“prefix”是与e.Name.Namespace
返回的命名空间关联的标识符,“element-name”是e.Name.LocalName
返回的标识符>。Try changing your line to:
The
LocalName
part is the important part, as otherwise you are comparing equality of anXName
with astring
. Remember, XML supports names of the style "prefix:element-name". In that example, "prefix" is the identifier associated with the namespace returned bye.Name.Namespace
and "element-name" is the identifier returned bye.Name.LocalName
.柯克的答案是正确的。我想指出您的代码的一些问题。
此行不必要地计算所有元素:
您可以将其替换为
Any()
,一旦找到元素,它将提前终止:接下来,验证
hasMatch
为true
你应该调用First()
而不是FirstOrDefault()
因为你知道它此时必须有一个值。话虽如此,您实际上可以按如下方式重写代码:
这里转换为
string
将返回该元素的值(如果找到),否则将返回null
。使用强制转换只是为了防止它为null
,因为您将无法使用matchingElement.Value
,如果没有,则会抛出NullReferenceException
发现了元素。如果您希望只存在一个元素,您还应该考虑使用SingleOrDefault
。Kirk's answer is right on the money. I wanted to point out a few issues with your code.
This line unnecessarily counts all the elements:
You can replace it with
Any()
which will terminate early once an element is found:Next, having verified that
hasMatch
istrue
you should callFirst()
instead ofFirstOrDefault()
since you know it has to have a value at that point.Having said that, you could actually rewrite your code as follows:
Here casting to a
string
will return the value of the element if it was found, otherwise it would returnnull
. The cast is used just in case it wasnull
since you wouldn't be able to usematchingElement.Value
which would throw aNullReferenceException
if no element was found. You should also consider usingSingleOrDefault
if you expect only one element to exist.我认为您需要将根命名空间添加到元素的名称中。
您还可以尝试使用
XContainer.Descendants(XName)
方法。I think you need to add the root namespace to the name of the element.
You can also try using the
XContainer.Descendants(XName)
method instead.