Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert DOCTYPE element in XmlDocument

Tags:

c#

.net

xml

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?

like image 962
TonE Avatar asked Nov 18 '25 20:11

TonE


1 Answers

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 };
like image 142
Codor Avatar answered Nov 20 '25 10:11

Codor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!