Search code examples
c#xmllinq-to-xmlxmlwriter

Namespace redefinition exception if XmlTextWriter is declared a certain way


I am bulding up an XDocument and serializing it to a UTF8 string with the following code:

string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
  using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
  {
    doc.Save(xw);
    xw.Flush();
    StreamReader sr = new StreamReader(ms);
    ms.Seek(0, SeekOrigin.Begin);
    xmlString = sr.ReadToEnd();
  }
}

This worked fine.

I then needed to toggle whether or not the declarator was serialized to the string. I changed the code to this:

string xmlString = "";
using (MemoryStream ms = new MemoryStream())
{
  XmlWriterSettings settings = new XmlWriterSettings()
  {
    OmitXmlDeclaration = !root.IncludeDeclarator,
    Encoding = Encoding.UTF8
  };
  using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
  {
    doc.Save(xw);
    xw.Flush();
    StreamReader sr = new StreamReader(ms);
    ms.Seek(0, SeekOrigin.Begin);
    xmlString = sr.ReadToEnd();
  }
}

This throws the following exception on doc.Save(xw):

The prefix '' cannot be redefined from '' to 'my_schema_here' within the same start element tag.

I am trying to figure out why the XDoc can be saved if the writer is "new"ed up, but not if it is ".Create"d. Any ideas?

Jordon


Solution

  • I fixed this by adding the namespace to the name of the root element in the XDocument. Still, it's strange that this isn't necessary if "new XmlTextWriter()" is used instead of "XmlTextWriter.Create()" or "XmlWriter.Create()".

    Jordon