Namespace redefinition exception if XmlTextWriter is declared a certain way

374 Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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