How to remove all namespaces from XML with C#?

前端 未结 30 2542
悲哀的现实
悲哀的现实 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条回答
  •  -上瘾入骨i
    2020-11-22 13:36

    the obligatory answer using LINQ:

    static XElement stripNS(XElement root) {
        return new XElement(
            root.Name.LocalName,
            root.HasElements ? 
                root.Elements().Select(el => stripNS(el)) :
                (object)root.Value
        );
    }
    static void Main() {
        var xml = XElement.Parse(@"
        
          
            0174587
            014717
            019172
            
            
              
              
    false
    Some state
    "); Console.WriteLine(stripNS(xml)); }

提交回复
热议问题