简体   繁体   English

检查XML节点是否具有Linq C#属性?

[英]Check if XML-node has attribute with Linq C#?

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: 我有一个包含几个节点的XML文件,如下所示:

<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" />

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. 现在,当存在PrefixValue时,我应该将该属性中的值添加到字符串前面,这并不是很困难,但是当我尝试查看PrefixValue属性是否存在时,我遇到了一些问题。节点。 In the instances where no PrefixValue is present, the attribute PrefixValue will not exist in the node at all. 在不存在PrefixValue的情况下,该节点中根本不存在属性PrefixValue。 How would I go about checking to see if the attribute exists with a Linq-expression? 我将如何检查该属性是否存在Linq表达式?

Well, it depends what you want to do. 好吧,这取决于您要做什么。 If you want to use it in a projection, you can use: 如果要在投影中使用它,可以使用:

(string) element.Attribute("PrefixValue")

That will return null if the attribute is missing, which is useful. 如果缺少该属性,它将返回null,这很有用。

If you want it in a where clause, use something like: 如果要在where子句中使用,请使用类似以下内容的方法:

where element.Attribute("PrefixValue") != null
if ((string)level1.Attribute("customer_code") != null)
{
   newBox.customer_code = (string)level1.Attribute("customer_code").Value;
}

The code above should take care of checking if the attribute exists. 上面的代码应注意检查属性是否存在。

Without the if statement you will get an object not set to an instance error. 如果没有if语句,您将得到一个未设置为实例错误的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM