How to remove all namespaces from XML with C#?

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

    This is a solution based on Peter Stegnar's accepted answer.

    I used it, but (as andygjp and John Saunders remarked) his code ignores attributes.

    I needed to take care of attributes too, so I adapted his code. Andy's version was Visual Basic, this is still c#.

    I know it's been a while, but perhaps it'll save somebody some time one day.

        private static XElement RemoveAllNamespaces(XElement xmlDocument)
        {
            XElement xmlDocumentWithoutNs = removeAllNamespaces(xmlDocument);
            return xmlDocumentWithoutNs;
        }
    
        private static XElement removeAllNamespaces(XElement xmlDocument)
        {
            var stripped = new XElement(xmlDocument.Name.LocalName);            
            foreach (var attribute in
                    xmlDocument.Attributes().Where(
                    attribute =>
                        !attribute.IsNamespaceDeclaration &&
                        String.IsNullOrEmpty(attribute.Name.NamespaceName)))
            {
                stripped.Add(new XAttribute(attribute.Name.LocalName, attribute.Value));
            }
            if (!xmlDocument.HasElements)
            {
                stripped.Value = xmlDocument.Value;
                return stripped;
            }
            stripped.Add(xmlDocument.Elements().Select(
                el =>
                    RemoveAllNamespaces(el)));            
            return stripped;
        }
    

提交回复
热议问题