【问题标题】:What's the easiest way to remove all attributes from a XML in C#?在 C# 中从 XML 中删除所有属性的最简单方法是什么?
【发布时间】:2011-04-02 13:11:35
【问题描述】:

我想从 XML 中删除所有标签的属性(我只想保留标签及其内部值)。在 C# 中最简单的方法是什么?

【问题讨论】:

    标签: xml regex parsing


    【解决方案1】:
    static void removeAllAttributes(XDocument doc)
    {
        foreach (var des in doc.Descendants())
            des.RemoveAttributes();
    }
    

    用法:

    var doc = XDocument.Load(path); //Or .Parse("xml");
    removeAllAttributes(doc);
    
    string res = doc.ToString();
    

    【讨论】:

      【解决方案2】:
      foreach (XmlElement el in nodes.SelectNodes(".//*")) {
         el.Attributes.RemoveAll();
      }
      

      【讨论】:

        【解决方案3】:

        如果您使用更好的 XPath,例如 "//*[@*]",它会更快

        foreach (XmlElement el in nodes.SelectNodes("//*[@*]")) {
           el.Attributes.RemoveAll();
        }
        

        这会将结果限制为仅具有属性的元素。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-11-12
          • 1970-01-01
          • 1970-01-01
          • 2010-09-23
          • 2012-07-11
          • 2016-08-31
          • 2017-12-25
          相关资源
          最近更新 更多