读取xml文件并根据xsd模式重新排列元素

时间:2014-05-16 17:51:43

标签: c# xml xsd

我有一个由我的应用程序创建的XML文件。我遇到的问题是xml文件中的元素与XSD文件的顺序不同(为了让供应商处理文件的要求)。

我的XSD文件摘要是:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="Vehicle">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Ford" minOccurs="0" maxOccurs="1">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="SectionA" minOccurs="0" maxOccurs="1">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="AX010_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX040_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX050_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX190_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="A080_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX230F_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX230G_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX230GNOTE_1" type="ExplanatoryText" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX230H_1" type="Dollar" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX230HNOTE_1" type="ExplanatoryText" minOccurs="0" maxOccurs="1"/>
                                        <xs:element name="AX230J_1" type="ExplanatoryText" minOccurs="0" maxOccurs="1"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>  

我的xml文件摘要是:

<SectionA>
   <AX010_1>121</AX010_1>
   <AX050_1>334122</AX050_1>
   <AX090_1>113</AX090_1>
   <AX040_1>334477</AX040_1>
   <AX230H_1>301</AX230H_1>
   <AX230F_1>3651122</AX230F_1>
</SectionA> 

如何读取XML文件并重新排列元素,使它们与XSD文件的顺序相同?

我在SO上看了类似的帖子,但我无法解决我的问题(更喜欢使用LINQToXML)。

1 个答案:

答案 0 :(得分:0)

如果要与c#类进行序列化,请在XmlElementAttribute上设置“Order”属性。 xsd.exe会使用/order选项为您生成这些属性。

[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public string AX010_1 { get; set; }
[System.Xml.Serialization.XmlElementAttribute(Order=1)]
public string AX040_1 { get; set; }

然后使用System.Xml.Serialization.XmlSerializer将序列化时节点命令。

相关问题