How to remove all namespaces from XML with C#?

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

    And this is the perfect solution that will also remove XSI elements. (If you remove the xmlns and don't remove XSI, .Net shouts at you...)

    string xml = node.OuterXml;
    //Regex below finds strings that start with xmlns, may or may not have :and some text, then continue with =
    //and ", have a streach of text that does not contain quotes and end with ". similar, will happen to an attribute
    // that starts with xsi.
    string strXMLPattern = @"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
    xml = Regex.Replace(xml, strXMLPattern, "");
    

提交回复
热议问题