How to remove xmlns attribute from XDocument?

前端 未结 1 828
暖寄归人
暖寄归人 2021-01-02 00:39

In my C# codebase, I have an XDocument of the form:


 
   

        
相关标签:
1条回答
  • 2021-01-02 01:20

    It seems the namespace information are kept in two places in the object tree that represents the XML document in LINQ to XML: as actual xmlns attributes and inside the elements' Names. If you remove it from both places it's gone:

    doc.Descendants()
       .Attributes()
       .Where( x => x.IsNamespaceDeclaration )
       .Remove();
    
    foreach (var elem in doc.Descendants())
        elem.Name = elem.Name.LocalName;
    

    (The first part of the code above is copied from now deleted answer by Bertrand Marron.)

    If you wanted to remove namespaces from attributes too, that's little more complicated, because their Name is read-only:

    foreach (var attr in doc.Descendants().Attributes())
    {
        var elem = attr.Parent;
        attr.Remove();
        elem.Add(new XAttribute(attr.Name.LocalName, attr.Value));
    }
    
    0 讨论(0)
提交回复
热议问题