How to remove all namespaces from XML with C#?

前端 未结 30 2555
悲哀的现实
悲哀的现实 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条回答
  •  臣服心动
    2020-11-22 13:52

    That will do the trick :-)

    foreach (XElement XE in Xml.DescendantsAndSelf())
    {
        // Stripping the namespace by setting the name of the element to it's localname only
        XE.Name = XE.Name.LocalName;
        // replacing all attributes with attributes that are not namespaces and their names are set to only the localname
        XE.ReplaceAttributes((from xattrib in XE.Attributes().Where(xa => !xa.IsNamespaceDeclaration) select new XAttribute(xattrib.Name.LocalName, xattrib.Value)));
    }
    

提交回复
热议问题