Force XDocument does not use a namespace prefix if the namespace is also defined as the default

I have an xml file with a default namespace specified with and without prefix space. When I generate xml output, I get all xml elements with a prefix. Is there a way to get rid of prefixes as I use the default namespace?

class Program { static void Main(string[] args) { var xml = "<root xmlns='default-namespace' xmlns:key='default-namespace'>" + " <node1></node1>" + " <node2></node2>" + "</root>"; var document = XDocument.Parse(xml); var output = document.ToString(); } } 

Output:

 <key:root xmlns="default-namespace" xmlns:key="default-namespace"> <key:node1></key:node1> <key:node2></key:node2> </key:root> 

What I expect:

 <root xmlns="default-namespace" xmlns:key="default-namespace"> <node1></node1> <node2></node2> </root> 

Unfortunately, I cannot delete the duplicate namespace declaration. The actual xml file I'm using is provided by the other side and I need to make as few changes as possible.

+5
source share
1 answer

You can use the String.Replace method to get the required XML format ...

 var xml ="<root xmlns='default-namespace' xmlns:key='default-namespace'>" + " <node1></node1>" + " <node2></node2>" + "</root>"; var document = XDocument.Parse(xml); var output = document.ToString().Replace("key:", string.Empty); 
-2
source

All Articles