【问题标题】:How to decide order of xml element?如何确定xml元素的顺序?
【发布时间】:2017-05-22 04:12:04
【问题描述】:

我有一个具有属性主体的通用基类和另一个具有属性标头的派生类,当我将派生类反序列化为 xml 时,它首先将主体作为第一个元素,然后是标头(按字母顺序反序列化),但我首先要标头然后是身体。我已经尝试过 XmlElement 的 order 属性,但它不起作用

示例类:

[XmlRoot("BaseClass", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class BaseClass<T>
{
   public T Body { get; set; }
}

[XmlRoot("DerivedClass", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class DerivedClass<THeader, TBody> : BaseClass<TBody>
where THeader : IEnvelopeHeader where TBody : class, IEnvelopeBody, new()
{
    public THeader Header { get; set; }
}

我看到了一个解决方案,它说将基类中的属性设为抽象并在派生类中覆盖,然后决定顺序,但我不能采用这个解决方案,因为我的基类也用于其他一些项目。

【问题讨论】:

标签: c# xml deserialization xml-serialization xml-deserialization


【解决方案1】:

我现在已经通过删除继承解决了顺序问题,但这不是我想要实现的,我所需要的只是按照定义的顺序对 xml 元素进行排序,即使您使用的是继承链。

[XmlRoot("Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope<THeader, TBody>
where THeader : IEnvelopeHeader where TBody : class, IEnvelopeBody, new()
{
    [XmlElement(ElementName = "Header", Order = 1)]
    public THeader Header { get; set; }

    [XmlElement(ElementName = "Body", Order = 2)]
    public TBody Body { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2016-09-12
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多