【发布时间】:2012-04-28 12:16:50
【问题描述】:
我想使用 XmlSerializer 序列化一个对象,并希望它使用 XSD 中定义的顺序。
例如,我有一个 XSD,其元素如下:
...
<xs:element name="Screen" minOccurs="1" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="Yaxis" minOccurs="1" maxOccurs="1" type="ab:AxisType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
...
<xs:complexType name="AxisType">
<xs:sequence>
<xs:group ref="ab:IntervalSegmentGroup" minOccurs="1" maxOccurs="unbounded"/>
<xs:element name="LastPoint" minOccurs="1" maxOccurs="1" type="ab:PointType" />
</xs:sequence>
</xs:complexType>
<xs:group name="IntervalSegmentGroup">
<xs:sequence>
<xs:element name="Point" minOccurs="1" maxOccurs="1" type="ab:PointType"/>
<xs:element name="Interpolation" minOccurs="1" maxOccurs="1" type="xs:string"/>
</xs:sequence>
</xs:group>
<xs:complexType name="PointType">
<xs:sequence>
<xs:element name="Relative" type="xs:decimal" minOccurs="1" maxOccurs="1"/>
<xs:element name="Absolute" type="xs:decimal" minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
...
然后我使用 XSD.exe 为此创建存根类。 然后我从这些分类中创建对象并用数据填充它们。然后我用 XMLSerializer 对它们进行序列化。
我想要得到的结果是这样的:
...
<Yaxis>
<Point>
<Relative>0</Relative>
<Absolute>0</Absolute>
</Point>
<Interpolation>linear</Interpolation>
<Point>
<Relative>0.456</Relative>
<Absolute>100</Absolute>
</Point>
<Interpolation>linear</Interpolation>
<Point>
<Relative>0.645</Relative>
<Absolute>342</Absolute>
</Point>
<Interpolation>linear</Interpolation>
<LastPoint>
<Relative>1</Relative>
<Absolute>3920</Absolute>
</LastPoint>
</Yaxis>
...
但我得到的是:
...
<Yaxis>
<Point>
<Relative>0</Relative>
<Absolute>0</Absolute>
</Point>
<Point>
<Relative>0.456</Relative>
<Absolute>100</Absolute>
</Point>
<Point>
<Relative>0.645</Relative>
<Absolute>342</Absolute>
</Point>
<Interpolation>linear</Interpolation>
<Interpolation>linear</Interpolation>
<Interpolation>linear</Interpolation>
<LastPoint>
<Relative>1</Relative>
<Absolute>3920</Absolute>
</LastPoint>
</Yaxis>
...
当我尝试根据 XSD 验证 XML 时,它将失败,因为它没有确认顺序点、插值、点...
我做错了什么?我可以通过某种方式控制它吗?
【问题讨论】:
-
也许
XSD.exe创建的存根类是这样排序的。如果可以的话,您也可以发布生成的存根类,以帮助我们回答您的问题。 -
linear 是否与您的相关?那么,您不会在架构中缺少一个额外的级别吗?我的观点是:“顺序”不是表明您的实际架构有问题,您应该重构它吗?
标签: c# .net serialization xsd xml-serialization