How to remove all namespaces from XML with C#?

前端 未结 30 2553
悲哀的现实
悲哀的现实 2020-11-22 13:30

I am looking for the clean, elegant and smart solution to remove namespacees from all XML elements? How would function to do that look like?

Defined interface:

30条回答
  •  旧时难觅i
    2020-11-22 13:40

    The tagged most useful answer has two flaws:

    • It ignores attributes
    • It doesn't work with "mixed mode" elements

    Here is my take on this:

     public static XElement RemoveAllNamespaces(XElement e)
     {
        return new XElement(e.Name.LocalName,
          (from n in e.Nodes()
            select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
              (e.HasAttributes) ? 
                (from a in e.Attributes() 
                   where (!a.IsNamespaceDeclaration)  
                   select new XAttribute(a.Name.LocalName, a.Value)) : null);
      }          
    

    Sample code here.

提交回复
热议问题