C# XElement how do I add different attributes in a specific order?

219 views Asked by At

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?

0

There are 0 answers