27

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?

2 Answers 2

58

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
Sign up to request clarification or add additional context in comments.

6 Comments

Essentially, I just want a null value to be returned if the attribute is missing altogether as a first step. Thanks!
@Ziggler: That suggests you're using an XNode rather than an XElement. We can't see any of your code, but basically you want to use XElement...
If it is XmlDocument, I am getting error XNode doesnot have Attribute property or method...and if it is XDocument, I have Attribute method for XElement but not string input..
@Ziggler: I have no idea what you mean I'm afraid, but it sounds like you should ask a new question showing us your code.
My question is if we take element as XElement in above answer... element.Attribute("PrefixValue") is showing me error since Attribute method is asking for XName not string.
|
5
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.