How do I add a custom XmlDeclaration with XmlDocument/XmlDeclaration?

25,487

Solution 1

What you are wanting to create is not an XML declaration, but a "processing instruction". You should use the XmlProcessingInstruction class, not the XmlDeclaration class, e.g.:

XmlDocument doc = new XmlDocument();
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
doc.AppendChild(declaration);
XmlProcessingInstruction pi = doc.CreateProcessingInstruction("MyCustomNameHere", "attribute1=\"val1\" attribute2=\"val2\"");
doc.AppendChild(pi);

Solution 2

You would want to append a XmlProcessingInstruction created using the CreateProcessingInstruction method of the XmlDocument.

Example:

XmlDocument document        = new XmlDocument();
XmlDeclaration declaration  = document.CreateXmlDeclaration("1.0", "ISO-8859-1", "no");

string data = String.Format(null, "attribute1=\"{0}\" attribute2=\"{1}\"", "val1", "val2");
XmlProcessingInstruction pi = document.CreateProcessingInstruction("MyCustomNameHere", data);

document.AppendChild(declaration);
document.AppendChild(pi);
Share:
25,487
Metro Smurf
Author by

Metro Smurf

By Day: Senior application architect. By Night: Currently interested in the structural (aka, dynamic) typing of JavaScript vs static typing of C#. PC Master Race: Crysis, Batman, BioShock, Metro 2033/Last Light, Ryse: Sone of Rome, Portal, Half-Life. The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. -- E.W.Dijkstra

Updated on December 03, 2020

Comments

  • Metro Smurf
    Metro Smurf over 3 years

    I would like to create a custom XmlDeclaration while using the XmlDocument/XmlDeclaration classes in c# .net 2 or 3.

    This is my desired output (it is an expected output by a 3rd party app):

    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <?MyCustomNameHere attribute1="val1" attribute2="val2" ?>
    [ ...more xml... ]
    

    Using the XmlDocument/XmlDeclaration classes, it appears I can only create a single XmlDeclaration with a defined set of parameters:

    XmlDocument doc = new XmlDocument();
    XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
    doc.AppendChild(declaration);
    

    Is there a class other than the XmlDocument/XmlDeclaration I should be looking at to create the custom XmlDeclaration? Or is there a way with the XmlDocument/XmlDeclaration classes itself?

  • Metro Smurf
    Metro Smurf over 15 years
    @Oppositional - Thanks again :) Bradely and you both nailed it.