Add the XAttribute to XElement if attribute exists in the element

Need to add

XAttribute newatt = new XAttribute("TAG", value); 

to XElement elem, but the elem could already contain the attribute with the name "TAG", so the elem.Add(newatt); would give error. The workaround I use at the moment is to check first:

if (elem.Attribute("TAG") != null) // check if attribute exists                        
    elem.SetAttributeValue("TAG", newatt.Value.ToString()); // Attribute exists
else
    elem.Add(newatt); // Attribute does not exist

Is there a shorter way to do this task, perhaps already available XElement function that checks for the existing "TAG" maybe (I am aware that it is possible to wrap the above snippet into a function)?

Jon Skeet
people
quotationmark

You don't need to check whether the attribute already exists before using SetAttributeValue. Just:

// Unconditional
elem.SetAttributeValue("TAG", value);

(There's no point even creating the XAttribute yourself.)

From the documentation:

The value is assigned to the attribute with the specified name. If no attribute with the specified name exists, a new attribute is added. If the value is null, the attribute with the specified name, if any, is deleted.

people

See more on this question at Stackoverflow