[英]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);
到
XElement elem
,但是elem
可能已经包含名称为"TAG"
的属性,因此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)? 有没有一种较短的方法可以执行此任务,也许已经可用的
XElement
函数可以检查现有的"TAG"
(我知道可以将上述代码片段包装为一个函数)?
You don't need to check whether the attribute already exists before using SetAttributeValue
. 在使用
SetAttributeValue
之前,无需检查属性是否已经存在。 Just: 只是:
// Unconditional
elem.SetAttributeValue("TAG", value);
(There's no point even creating the XAttribute
yourself.) (甚至没有
XAttribute
自己创建XAttribute
。)
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.
如果该值为null,则删除具有指定名称(如果有)的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.