How to remove all namespaces from XML with C#?

前端 未结 30 2225
悲哀的现实
悲哀的现实 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:41

    Bit late to the party on this one but here's what I used recently:

    var doc = XDocument.Parse(xmlString);
    doc.Root.DescendantNodesAndSelf().OfType().Attributes().Where(att => att.IsNamespaceDeclaration).Remove();
    

    (taken from this MSDN Thread)

    Edit As per the comment below, it appears that while this removes the namespace prefix from the nodes it doesn't actually remove the xmlns attribute. To do that you need to also reset the name of each node to it's localname (eg name minus namespace)

    foreach (var node in doc.Root.DescendantNodesAndSelf().OfType())
    {
        node.Name = node.Name.LocalName;
    }
    

提交回复
热议问题