C#: How to remove namespace information from XML elements

前端 未结 3 704
面向向阳花
面向向阳花 2020-12-16 02:18

How can I remove the \"xmlns:...\" namespace information from each XML element in C#?

3条回答
  •  渐次进展
    2020-12-16 03:06

    From here http://simoncropp.com/working-around-xml-namespaces

    var xDocument = XDocument.Parse(
    @"
        
            African Coffee Table
            80
            120
        
      ");
    
    xDocument.StripNamespace();
    var tables = xDocument.Descendants("table");
    
    public static class XmlExtensions
    {
        public static void StripNamespace(this XDocument document)
        {
            if (document.Root == null)
            {
                return;
            }
            foreach (var element in document.Root.DescendantsAndSelf())
            {
                element.Name = element.Name.LocalName;
                element.ReplaceAttributes(GetAttributes(element));
            }
        }
    
        static IEnumerable GetAttributes(XElement xElement)
        {
            return xElement.Attributes()
                .Where(x => !x.IsNamespaceDeclaration)
                .Select(x => new XAttribute(x.Name.LocalName, x.Value));
        }
    }
    

提交回复
热议问题