Proper name space management in .NET XmlWriter Proper name space management in .NET XmlWriter xml xml

Proper name space management in .NET XmlWriter


Use this code:

using (var writer = XmlWriter.Create("file.xml")){    const string Ns = "http://bladibla";    const string Prefix = "abx";    writer.WriteStartDocument();    writer.WriteStartElement("root");    // set root namespace    writer.WriteAttributeString("xmlns", Prefix, null, Ns);    writer.WriteStartElement(Prefix, "child", Ns);    writer.WriteAttributeString("id", "A");    writer.WriteStartElement("grandchild");    writer.WriteAttributeString("id", "B");    writer.WriteElementString(Prefix, "grandgrandchild", Ns, null);    // grandchild    writer.WriteEndElement();    // child    writer.WriteEndElement();    // root    writer.WriteEndElement();    writer.WriteEndDocument();}

This code produced desired output:

<?xml version="1.0" encoding="utf-8"?><root xmlns:abx="http://bladibla">  <abx:child id="A">    <grandchild id="B">      <abx:grandgrandchild />    </grandchild>  </abx:child></root>


Did you try this?

Dim settings = New XmlWriterSettings With {.Indent = True,                                          .NamespaceHandling = NamespaceHandling.OmitDuplicates,                                          .OmitXmlDeclaration = True}Dim s As New MemoryStreamUsing writer = XmlWriter.Create(s, settings)    ...End Using

Interesting is the 'NamespaceHandling.OmitDuplicates'


I'm not sure this is what you're looking for, but you can use this kind of code when you start writing to the Xml stream:

myWriter.WriteAttributeString("xmlns", "abx", null, "http://bladibla");

The XmlWriter should remember it and not rewrite it anymore. It may not be 100% bulletproof, but it works most of the time.