首页 > 解决方案 > C# XElement 如何按特定顺序添加不同的属性?

问题描述

我有以下 C# 代码来生成 XML 文档。问题是我需要交换标签“CState”中属性的顺序。因此,我已经尝试了几件事。不幸的是它不起作用或我得到一个例外。

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"))
         
                    ));

这是 XML 文件中的输出。

<?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>

但是,属性应该以不同的顺序出现。

这是 XML 文件中第二行的创建方式(不正确):

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

这是在 XML 文件中创建第二行的方式(正确):

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

我怎样才能尽可能容易地做到这一点?

标签: c#xmlxelementxattribute

解决方案


推荐阅读