Search code examples
c#xmlprocessing-instruction

how to add processing instruction in xml using XmlDocument


I am writing a XML using XmlDocument, I need a element or attribute like shown below

The element or attribute required is <?Validversion="1" ?>

how to create using xmldocument or xmlwriter.

        // to create <?Validversion="1" ?>
        XmlDocument aDoc = new XmlDocument();
        aDoc.CreateXmlDeclaration("1.0", "utf-16", null);
        XmlCDataSection aDataSec =aDoc.CreateCDataSection("?Version = 2");
        aDoc.AppendChild(aDataSec);
        aDoc.Save("c:\\vector.xml");

Solution

  • You are looking for XmlDocument.CreateProcessingInstruction and not CDATA section:

    var document = new XmlDocument();
    document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-16", null));
    var  piNode = document.CreateProcessingInstruction("Version", "=\"2\"");
    document.AppendChild(pi);
    

    Side note: don't forget to AppendChild newly created node.