TonE
TonE

Reputation: 3025

How to insert DOCTYPE element in XmlDocument

I have some production code which generates an XML file in the following way:

  1. Generate a string by using XmlSerializer with an instance of a class with XmlAttributes
  2. Generate XmlDocument by using LoadXml() with the string generated in step 1
  3. Write to file using XmlWriter wrapping a StringWriter

It is now required that a DOCTYPE declaration is included. I want to make as few changes as possible to the code.

The only way I have managed to do this so far is:

tx.WriteDocType("entitytype", null, "http://testdtd/entity.dtd", null);                    
foreach (XmlNode node in document)
{
  if (node.NodeType == XmlNodeType.XmlDeclaration)
  {
    document.RemoveChild(node);
  }
}
document.WriteTo(tx); 

This seems to be a bit of a hack - is there a better way I can insert a DOCTYPE declaration? In particular is there a way I can avoid having an XmlDeclaration in the XmlDocument generated by the LoadXml() call?

Upvotes: 3

Views: 3342

Answers (2)

jr-juxtaposition
jr-juxtaposition

Reputation: 315

Thanks Codor for your answer and discussion which helped me figure this out even though my code looks quite different from the code in the question.

My XmlDocument also had an XML declaration, so this worked for me:

XmlDocument doc = new XmlDocument();
doc.Load(templateFilename);
doc.InsertAfter(doc.CreateDocumentType("html", null, null, null), doc.FirstChild);

Otherwise, i suppose i would have used PrependChild() rather than InsertAfter().

Upvotes: 0

Codor
Codor

Reputation: 17605

Perhaps more steps in the conversion are necessary, but on serialization the xml declaration can be removed by using an instance of XmlWriterSettings configured as follows.

var iSettings = new XmlWriterSettings{ OmitXmlDeclaration = true };

Upvotes: 1

Related Questions