如何将XML反序列化为List <object> </object>

时间:2013-12-20 06:50:26

标签: c# xml asp.net-mvc asp.net-mvc-3 wcf

我尝试创建WCF,返回值为XML。 当我尝试将xml文件反序列化为对象时,我有错误。

这是我的反序列化文件的代码

我的控制器

//serialize request to wcf//    
var requestXML = Lib.Serializer.ObjectSerializer.Serialize(request);
//get response from wcf//
var XMLResult = Lib.Net.Http.Post(requestXML,"http://localhost:53721/RoomRate.svc/RoomRates", 60);
//deserialize xml file to object//
var response = Lib.Serializer.ObjectSerializer.Deserialize<List<RoomRatesResponses>>(XMLResult);

我的反序列化xml

的类
public static T Deserialize<T>(string xml)
{
    T result;
    XmlSerializer ser = new XmlSerializer(typeof(T));
    using (TextReader tr = new StringReader(xml))
    {
        result = (T)ser.Deserialize(tr);
    }
    return result;
}

我的对象模型

public class RoomRatesResponses
{
    public List<RoomRateResponse> ListRoomRateResponse { get; set; }

    public RoomRatesResponses()
    {
        ListRoomRateResponse = new List<RoomRateResponse>();
    }
}

public class RoomRateResponse
{
    public string ErrorMessage { get; set; }
    public bool OperationSuccess { get; set; }
    public int Allotment { get; set; }
    public bool Breakfast { get; set; }
    public DateTime CheckInDate { get; set; }
    public bool CloseSelling { get; set; }
    public double CommissionPct { get; set; }
    public string CurrCode { get; set; }
    public bool FreeSell { get; set; }
    public int RoomRateId { get; set; }
    public string RoomType { get; set; }
    public double SingleRate { get; set; }
    public double TripleRate { get; set; }
    public double TwinDoubleRate { get; set; }
}

当我反序列化我的xml时,我有这样的错误

  

<ArrayOfRoomRateResult xmlns=''>没有预料到。        描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪了解更多信息   有关错误的信息以及它在代码中的起源。

     

异常详细信息:System.InvalidOperationException<ArrayOfRoomRateResult xmlns=''>未被预期。

如何解析我的xml文件?

    <?xml version="1.0" encoding="utf-8"?>
<ArrayOfRoomRateResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <RoomRateResult>
    <OperationSuccess>true</OperationSuccess>
    <ErrorMessage/>
    <RoomRateId>1170</RoomRateId>
    <RoomType>superior</RoomType>
    <RoomTypeID>150</RoomTypeID>
    <Breakfast>true</Breakfast>
    <CheckInDate>2014-01-01T00:00:00</CheckInDate>
    <CurrCode>IDR</CurrCode>
    <SingleRate>450000.0000</SingleRate>
    <TwinDoubleRate>450000.0000</TwinDoubleRate>
    <TripleRate>750000.0000</TripleRate>
    <CommissionPct>15.00</CommissionPct>
    <Allotment>25</Allotment>
    <FreeSell>true</FreeSell>
    <CloseSelling>false</CloseSelling>
    <CancellationPolicy/>
  </RoomRateResult>
  <RoomRateResult>
    <OperationSuccess>true</OperationSuccess>
    <ErrorMessage/>
    <RoomRateId>1171</RoomRateId>
    <RoomType>superior</RoomType>
    <RoomTypeID>150</RoomTypeID>
    <Breakfast>true</Breakfast>
    <CheckInDate>2014-01-02T00:00:00</CheckInDate>
    <CurrCode>IDR</CurrCode>
    <SingleRate>450000.0000</SingleRate>
    <TwinDoubleRate>450000.0000</TwinDoubleRate>
    <TripleRate>750000.0000</TripleRate>
    <CommissionPct>15.00</CommissionPct>
    <Allotment>22</Allotment>
    <FreeSell>false</FreeSell>
    <CloseSelling>false</CloseSelling>
    <CancellationPolicy/>
  </RoomRateResult>
  <RoomRateResult>
    <OperationSuccess>true</OperationSuccess>
    <ErrorMessage/>
    <RoomRateId>1177</RoomRateId>
    <RoomType>deluxe</RoomType>
    <RoomTypeID>151</RoomTypeID>
    <Breakfast>false</Breakfast>
    <CheckInDate>2014-01-01T00:00:00</CheckInDate>
    <CurrCode>IDR</CurrCode>
    <SingleRate>600000.0000</SingleRate>
    <TwinDoubleRate>600000.0000</TwinDoubleRate>
    <TripleRate>850000.0000</TripleRate>
    <CommissionPct>25.00</CommissionPct>
    <Allotment>11</Allotment>
    <FreeSell>false</FreeSell>
    <CloseSelling>false</CloseSelling>
    <CancellationPolicy>
      <Cancellation>
        <CancellationPolicyID>34</CancellationPolicyID>
        <ValidFrom>2014-01-01T00:00:00</ValidFrom>
        <ValidTo>2014-01-31T00:00:00</ValidTo>
        <ValidDays>YYYYYYY</ValidDays>
        <ChargeTypeId>1</ChargeTypeId>
        <CancellationCharge>1.0000</CancellationCharge>
        <DayBeforeCheckIn>7</DayBeforeCheckIn>
      </Cancellation>
    </CancellationPolicy>
  </RoomRateResult>
  <RoomRateResult>
    <OperationSuccess>true</OperationSuccess>
    <ErrorMessage/>
    <RoomRateId>1178</RoomRateId>
    <RoomType>deluxe</RoomType>
    <RoomTypeID>151</RoomTypeID>
    <Breakfast>false</Breakfast>
    <CheckInDate>2014-01-02T00:00:00</CheckInDate>
    <CurrCode>IDR</CurrCode>
    <SingleRate>500000.0000</SingleRate>
    <TwinDoubleRate>500000.0000</TwinDoubleRate>
    <TripleRate>750000.0000</TripleRate>
    <CommissionPct>25.00</CommissionPct>
    <Allotment>22</Allotment>
    <FreeSell>false</FreeSell>
    <CloseSelling>false</CloseSelling>
    <CancellationPolicy>
      <Cancellation>
        <CancellationPolicyID>34</CancellationPolicyID>
        <ValidFrom>2014-01-01T00:00:00</ValidFrom>
        <ValidTo>2014-01-31T00:00:00</ValidTo>
        <ValidDays>YYYYYYY</ValidDays>
        <ChargeTypeId>1</ChargeTypeId>
        <CancellationCharge>1.0000</CancellationCharge>
        <DayBeforeCheckIn>7</DayBeforeCheckIn>
      </Cancellation>
    </CancellationPolicy>
  </RoomRateResult>
</ArrayOfRoomRateResult>

2 个答案:

答案 0 :(得分:1)

以下是解决问题所需的虚拟代码。它显示了序列化如何在这里工作,反向是要进行反序列化,注意类和变量名称:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Xml.Serialization;

namespace Code.Without.IDE
{
    //http://stackoverflow.com/questions/20697928/how-to-deserialize-xml-to-listobject
    public class Dummy
    {
        private static void Main()
        {
            List<RoomRateResult> ArrayOfRoomRateResult = new List<RoomRateResult>();
            RoomRateResult rs1 = new RoomRateResult
                                        {
                                            ErrorMessage = string.Empty,
                                            OperationSuccess = true,
                                            Allotment = 10,
                                            Breakfast = true,
                                            CheckInDate = DateTime.Now,
                                            CloseSelling = false,
                                            CommissionPct = 3.0d,
                                            CurrCode = "USD",
                                            FreeSell = true,
                                            RoomRateId = 100,
                                            RoomType = "Mega",
                                            SingleRate = 95d,
                                            TripleRate = 150d,
                                            TwinDoubleRate = 150d
                                        };

            RoomRateResult rs2 = new RoomRateResult
                                        {
                                            ErrorMessage = string.Empty,
                                            OperationSuccess = true,
                                            Allotment = 12,
                                            Breakfast = true,
                                            CheckInDate = DateTime.Now,
                                            CloseSelling = false,
                                            CommissionPct = 2.0d,
                                            CurrCode = "USD",
                                            FreeSell = true,
                                            RoomRateId = 110,
                                            RoomType = "Mega",
                                            SingleRate = 90d,
                                            TripleRate = 140d,
                                            TwinDoubleRate = 150d
                                        };

            ArrayOfRoomRateResult.Add(rs1);
            ArrayOfRoomRateResult.Add(rs2);

            XmlSerializer ser = new XmlSerializer(typeof(List<RoomRateResult>));
            TextWriter writer = new StreamWriter("serl.xml");
            ser.Serialize(writer, ArrayOfRoomRateResult);
            writer.Flush();
            writer.Close();
        }
    }

    [Serializable]
    public class RoomRateResult
    {
        public string ErrorMessage { get; set; }
        public bool OperationSuccess { get; set; }
        public int Allotment { get; set; }
        public bool Breakfast { get; set; }
        public DateTime CheckInDate { get; set; }
        public bool CloseSelling { get; set; }
        public double CommissionPct { get; set; }
        public string CurrCode { get; set; }
        public bool FreeSell { get; set; }
        public int RoomRateId { get; set; }
        public string RoomType { get; set; }
        public double SingleRate { get; set; }
        public double TripleRate { get; set; }
        public double TwinDoubleRate { get; set; }
    }
}

序列化给出:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfRoomRateResult xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <RoomRateResult>
    <ErrorMessage />
    <OperationSuccess>true</OperationSuccess>
    <Allotment>10</Allotment>
    <Breakfast>true</Breakfast>
    <CheckInDate>2013-12-19T23:11:08.2340815-08:00</CheckInDate>
    <CloseSelling>false</CloseSelling>
    <CommissionPct>3</CommissionPct>
    <CurrCode>USD</CurrCode>
    <FreeSell>true</FreeSell>
    <RoomRateId>100</RoomRateId>
    <RoomType>Mega</RoomType>
    <SingleRate>95</SingleRate>
    <TripleRate>150</TripleRate>
    <TwinDoubleRate>150</TwinDoubleRate>
  </RoomRateResult>
  <RoomRateResult>
    <ErrorMessage />
    <OperationSuccess>true</OperationSuccess>
    <Allotment>12</Allotment>
    <Breakfast>true</Breakfast>
    <CheckInDate>2013-12-19T23:11:08.2380815-08:00</CheckInDate>
    <CloseSelling>false</CloseSelling>
    <CommissionPct>2</CommissionPct>
    <CurrCode>USD</CurrCode>
    <FreeSell>true</FreeSell>
    <RoomRateId>110</RoomRateId>
    <RoomType>Mega</RoomType>
    <SingleRate>90</SingleRate>
    <TripleRate>140</TripleRate>
    <TwinDoubleRate>150</TwinDoubleRate>
  </RoomRateResult>
</ArrayOfRoomRateResult>

答案 1 :(得分:1)

如果你不想像Abhinav所说的那样出于某种原因重命名你的类,你可以创建自己的列表来实现 IXmlSerializable

[XmlRoot(ElementName = "ArrayOfRoomRateResult")]
public class MyList : List<RoomRateResponse>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        var serializer = new XmlSerializer(typeof(RoomRateResponse));
        var wasEmpty = reader.IsEmptyElement;
        reader.Read();
        if (wasEmpty)
            return;
        while (reader.NodeType != XmlNodeType.EndElement)
        {
            var item = (RoomRateResponse)serializer.Deserialize(reader);
            Add(item);
        }
        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer)
    {
        var serializer = new XmlSerializer(typeof(RoomRateResponse));
        foreach (var val in this)
        {
            serializer.Serialize(writer, val);
        }
    }
}

您还需要将属性添加到 RoomRateResponse

[XmlRoot(ElementName = "RoomRateResult")]
public class RoomRateResponse
{
    //...
}

现在您的序列化按预期工作:

//...
var response = Lib.Serializer.ObjectSerializer.Deserialize<MyList>(xml);