存在集合/列表和单个元素时,在C#中反序列化XML

时间:2018-11-28 10:46:07

标签: xml xml-parsing

我的XML如下:

<FreightResponse>
    <Rate>
        <Carrier>C1</Carrier>
        <Service>S1</Service>
        <PublishedRate>P1</PublishedRate>
        <DiscountedRate>D1</DiscountedRate>
        <EstmatedTime>E1</EstmatedTime>
    </Rate>
    <Rate>
    <Carrier>C2</Carrier>
        <Service>S2</Service>
        <PublishedRate>P2</PublishedRate>
        <DiscountedRate>D2</DiscountedRate>
        <EstmatedTime>E2</EstmatedTime>
    </Rate>
    <ERROR_RESPONSE>ABF Error response will be appear here
    </ERROR_RESPONSE>
</FreightResponse>

现在,我可以使用

获取费率详细信息
List<Rate> rateList = (List<Rate>)serializer.Deserialize(stringReader);

但是不知道如何使用序列化程序获取ERROR_RESPONSE值,我可以通过

获取
var errorMessage = rootElement.Element("ERROR_RESPONSE").Value;

但是我想知道如何使用序列化器

1 个答案:

答案 0 :(得分:0)

如果您使用的是“ XmlSerializer”,则下面的代码将起作用。

public class Rate {
    public string Carrier { get; set; }
    public string Service { get; set; }
    public string PublishedRate { get; set; }
    public string DiscountedRate { get; set; }
    public string EstmatedTime { get; set; }
}
[System.Xml.Serialization.XmlRoot("FreightResponse")]
public class FreightResponse {
    [System.Xml.Serialization.XmlElement("Rate")]
    public List<Rate> Rate { get; set; }
    public string ERROR_RESPONSE { get; set; }
}
FreightResponse rateList = (FreightResponse)serializer.Deserialize(stringReader);

在“ FreightResponse”类对象中具有“费率”对象的列表。