1

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
Edwardo
  • 872
  • 1
  • 11
  • 24
  • 1
    For the ` – canton7 Jan 05 '22 at 16:17
  • 1
    For the second, see https://stackoverflow.com/questions/8324960/creating-xdocument-with-xsischemalocation-namespace (but obviously replace schemaLocation with noNamespaceSchemaLocation) – canton7 Jan 05 '22 at 16:17

1 Answers1

1
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")
));
JohnyL
  • 6,894
  • 3
  • 22
  • 41