Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

xml

linq

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

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?

like image 933
Henric Avatar asked Mar 24 '10 10:03

Henric


People also ask

How do you check if a specific attribute exists or not in XML?

XML DOM hasAttribute() Method The hasAttribute() method returns TRUE if the current element node has the attribute specified by name, and FALSE otherwise.

Does LINQ work with XML?

The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes.

What is XElement C#?

The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.


2 Answers

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.

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

where element.Attribute("PrefixValue") != null 
like image 116
Jon Skeet Avatar answered Sep 23 '22 07:09

Jon Skeet


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.

like image 38
Vivek Avatar answered Sep 24 '22 07:09

Vivek