xmltextwritersystem.xml

Is there a way to have XmlTextWriter not write redundant name spaces


I am writing out all of my nodes and the XML I get is this:

<?xml version="1.0" encoding="utf-8"?>
<root attribute="xyz">
  <h:table xmlns:h="http://www.windward.net" attribute="xyz">
    <h:tr xmlns:h="http://www.windward.net">
      <h:name xmlns:h="http://www.windward.net">windward</h:name>
      <h:width xmlns:h="http://www.windward.net">42</h:width>
    </h:tr>
  </h:table>
  <f:table xmlns:f="http://www.windward2.net" attribute="xyz">
    <f:name xmlns:f="http://www.windward2.net">windward2</f:name>
    <f:width xmlns:f="http://www.windward2.net">42</f:width>
    <f:length xmlns:f="http://www.windward2.net">120</f:length>
  </f:table>
  <test>42</test>
</root>

Is there a way to have XmlTextWriter not repeat the xmlns:h & xmlns:f in the inner nodes?

This is for some code where adding nodes (the above is a simple example) I don't know for sure what namespaces have been added higher up in the DOM.


Solution

  • You can use an XmlWriter with XmlWriterSettings where the NamespaceHandling omits duplicates:

     using (XmlWriter xw = XmlWriter.Create(Console.Out, new XmlWriterSettings() { Indent = true, NamespaceHandling = NamespaceHandling.OmitDuplicates }))
            {
                doc.Save(xw);
            }
    

    XmlTextWriter is just a legacy (.NET 1.0) implementation of an XmlWriter, in terms of standards compliance XmlWriter.Create should not give you any disadvantage, unless you use some XmlTextWriter features that are more Microsoft specific than XML standard relevant.