如果元素中存在属性,则将XAttribute添加到XElement [英] Add the XAttribute to XElement if attribute exists in the element
问题描述
需要添加
XAttribute newatt = new XAttribute("TAG", value);
到XElement elem
,但是elem
可能已经包含名称为"TAG"
的属性,因此elem.Add(newatt);
将给出错误.我目前使用的解决方法是先检查:
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
是否有较短的方法可以执行此任务,也许已经可用的XElement
函数可以检查现有的"TAG"
(我知道可以将上述代码片段包装为一个函数)?
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)?
推荐答案
在使用SetAttributeValue
之前,无需检查属性是否已经存在.只是:
You don't need to check whether the attribute already exists before using SetAttributeValue
. Just:
// Unconditional
elem.SetAttributeValue("TAG", value);
(甚至自己创建XAttribute
也没有意义.)
(There's no point even creating the XAttribute
yourself.)
来自文档:
该值已分配给具有指定名称的属性.如果不存在具有指定名称的属性,则添加新属性.如果该值为null,则删除具有指定名称的属性(如果有).
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.
这篇关于如果元素中存在属性,则将XAttribute添加到XElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!