【问题标题】:Add the XAttribute to XElement if attribute exists in the element如果元素中存在属性,则将 XAttribute 添加到 XElement
【发布时间】:2017-07-19 10:34:57
【问题描述】:

需要补充

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

XElement elem,但elem 可能已经包含名称为"TAG" 的属性,因此elem.Add(newatt); 会出错。我目前使用的解决方法是先检查:

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" 可能(我知道可以将上述 sn-p 包装到函数中)?

【问题讨论】:

    标签: c# xml linq xelement


    【解决方案1】:

    在使用SetAttributeValue之前不需要检查属性是否已经存在。只是:

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

    (甚至自己创建XAttribute 也没有意义。)

    来自documentation

    将值分配给具有指定名称的属性。如果不存在具有指定名称的属性,则添加一个新属性。如果值为 null,则删除具有指定名称的属性(如果有)。

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      相关资源
      最近更新 更多