0

I have the following C# code to generate an XML document. The problem is that I need to swap the order of the attributes in the tag "CState". Therefore I have already tried several things. Unfortunately it does not work or I get an exception.

XNamespace ns = "http:dev.test.com/Job/Con";
                XNamespace nsi = "http:www.w3.org/2001/XMLSchema-instance";
                XElement doc = new XElement(ns + "CState", new XAttribute(XNamespace.Xmlns + "xsi", nsi),

                new XElement(ns + "Page",
                new XElement(ns + "Field", new XAttribute("dName", "MembershipNumber"), new XAttribute("type", "Text"), new XAttribute("value", "123456")),
                new XElement(ns + "Field", new XAttribute("dName", "FirstName"), new XAttribute("type", "Text"), new XAttribute("value", "Michael")),
                new XElement(ns + "Field", new XAttribute("dName", "LastName"), new XAttribute("type", "Text"), new XAttribute("value", "Hendly"))
         
                    ));

This is the output in the XML file.

<?xml version="1.0" encoding="utf-8"?>
<CState xmlns:xsi="http:www.w3.org/2001/XMLSchema-instance" xmlns="http:dev.test.com/Job/Con">
  <Page>
    <Field dName="MembershipNumber" type="Text" value="123456" />
    <Field dName="FirstName" type="Text" value="Michael" />
    <Field dName="LastName" type="Text" value="Hendly" />
  </Page>
</ControlStatements>

However, the attributes should appear in a different order.

This is how the second line in the XML file is created (incorrect):

<CState xmlns:xsi="http:www.w3.org/2001/XMLSchema-instance" xmlns="http:dev.test.com/Job/Con">

This is how the second line should be created in the XML file (correct):

<CState xmlns="http:dev.test.com/Job/Con" xmlns:xsi="http:www.w3.org/2001/XMLSchema-instance">

How can I achieve this as easily as possible?

Philipp Ape
  • 519
  • 3
  • 13
ThoDan
  • 43
  • 4
  • 2
    According to the XML [specification](https://www.w3.org/TR/xml/#sec-starttags), the order of attributes does not matter. – Alexander Petrov Jul 14 '21 at 13:00
  • That's right. Unfortunately, the application that needs to read the XML file does not see it that way. There the import fails if the order is "wrong". – ThoDan Jul 14 '21 at 13:01
  • Try if this helps: https://stackoverflow.com/a/34718956/1220550 – Peter B Jul 14 '21 at 13:26

0 Answers0