检查XML节点已与LINQ的C#属性? [英] Check if XML-node has attribute with Linq C#?

查看:166
本文介绍了检查XML节点已与LINQ的C#属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查,看看如果一个节点实际上有一定的属性?我有一个包含多个节点看起来像这样的XML文件:

How can I check and see if a node actually has a certain attribute? I have an XML-file containing several nodes looking like this:

<Field From="OldString" To="NewString" /> 



到目前为止好。问题是,这种结构是即将被改变,一些节点将是这样的:

So far so good. The problem is that this structure is about to be changed to that some nodes will look like this:

<Field From="OldString" To="NewString" PrefixValue="OptionalAttribute" />

现在,当PrefixValue存在我应该在该属性的值在前面加上一个字符串,那是不是很困难,但我遇到了一些问题,当我尝试看看是否PrefixValue属性出现在所有的节点。在没有PrefixValue是本实例中,属性PrefixValue不会在节点处存在。我怎么会去检查,看看属性与LINQ的表达存在?

Now, when the PrefixValue is present I am supposed to prepend the value in that attribute to a string, and that is not very difficult, but I have run into some problems when I try to see if the PrefixValue attribute is present at all for a node. In the instances where no PrefixValue is present, the attribute PrefixValue will not exist in the node at all. How would I go about checking to see if the attribute exists with a Linq-expression?

推荐答案

你想要什么嘛,这取决于去做。如果你想在投影使用它,你可以使用:

Well, it depends what you want to do. If you want to use it in a projection, you can use:

(string) element.Attribute("PrefixValue")

这将返回null如果属性丢失,这是非常有用的。

That will return null if the attribute is missing, which is useful.

如果你想让它在where子句中,使用这样的:

If you want it in a where clause, use something like:

where element.Attribute("PrefixValue") != null

这篇关于检查XML节点已与LINQ的C#属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆