Reputation: 3025
I have some production code which generates an XML file in the following way:
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
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
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