How do I generate this XML in C#?

48 Views Asked by At

I have an example XML file that I need to generate on the fly in a console application.

This is an example of the first part of the required XML document:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="ABC123.xsl" ?>
<CPPData xsi:noNamespaceSchemaLocation="CPPData_V1.14.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Envelope>
        <EnvelopeNode NumOrdre="1">
        </EnvelopeNode>
    </Envelope>
</CPPData>

I have a method creates and returns an XElement which contains all the data required by the body of the XML (e.g. everything inside the CPPData element).

However I can't figure out how to add the following:

  1. <?xml-stylesheet type="text/xsl" href="ABC123.xsl" ?> to the XDocument
  2. <CPPData xsi:noNamespaceSchemaLocation="CPPData_V1.14.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> to the XElement
1

There are 1 best solutions below

0
JohnyL On
var xml = new XDocument();
var xp = new XProcessingInstruction(target: "xml-stylesheet", data: @"type=""text/xsl"" href=""ABC123.xsl""");
xml.Add(xp);
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
xml.Add(new XElement("root",
          new XAttribute(ns + "noNamespaceSchemaLocation", "CPPData_V1.14.xsd"),
          new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance")
));