How to remove all namespaces from XML with C#?

前端 未结 30 2559
悲哀的现实
悲哀的现实 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条回答
  •  Happy的楠姐
    2020-11-22 13:37

    I really liked where Dexter is going up there so I translated it into a “fluent” extension method:

    /// 
    /// Returns the specified 
    /// without namespace qualifiers on elements and attributes.
    /// 
    /// The element
    public static XElement WithoutNamespaces(this XElement element)
    {
        if (element == null) return null;
    
        #region delegates:
    
            Func getChildNode = e => (e.NodeType == XmlNodeType.Element) ? (e as XElement).WithoutNamespaces() : e;
    
            Func> getAttributes = e => (e.HasAttributes) ?
                e.Attributes()
                    .Where(a => !a.IsNamespaceDeclaration)
                    .Select(a => new XAttribute(a.Name.LocalName, a.Value))
                :
                Enumerable.Empty();
    
            #endregion
    
        return new XElement(element.Name.LocalName,
            element.Nodes().Select(getChildNode),
            getAttributes(element));
    }
    

    The “fluent” approach allows me to do this:

    var xml = File.ReadAllText(presentationFile);
    var xDoc = XDocument.Parse(xml);
    var xRoot = xDoc.Root.WithoutNamespaces();
    

提交回复
热议问题