Add the XAttribute to XElement if attribute exists in the element

*爱你&永不变心* 提交于 2019-12-20 04:37:37

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/45187985/add-the-xattribute-to-xelement-if-attribute-exists-in-the-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!