5

I have an xml file with default namespace specified with and without namespace prefix. When I generate xml output I'm getting all xml elements prefixed. Is there way to get rid of the prefixes since I'm using 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();
    }
}

The output:

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

What I'd expect:

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

Unfortunately I can't remove the duplicated namespace declaration. The actual xml file I'm using is provided by another party and I need to do as less modifications as possible.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
username
  • 3,378
  • 5
  • 44
  • 75
  • In my view it is a shortcoming of the LINQ to XML object models that prefixes of node names are not stored and that way the serializer has to choose a prefix based on namespace declaration attributes when serializing a tree to a string of XML. It seems that the current implementation of ToString() or Save uses the last found namespace declaration of a namespace as changing the order to `` gives a different result but that is not something to rely on obviously. If prefixes matter, choose a different tree model like XmlDocument. – Martin Honnen Sep 17 '15 at 14:21

1 Answers1

-2

You Can Use 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);
Alok
  • 342
  • 2
  • 8