如何将xml序列化/反序列化为C#对象?

如何将该XML字符串序列化/反序列化为C#对象?


<Response>

    <Business Number="99696" Name="My business" Address=""  />

    <Purchase PurchaseID="7" CustomerID="0" >

        <Item Name="item 1" Qty="100" UnitCost="10.0000" />

        <Item Name="item2" Qty="200" UnitCost="20.0000" />

    </Purchase>

</Response>

谢谢rubenc


我认为这是一个不同的问题,因为所有问题通常都涉及一个级别或一个项目列表


我的问题是我有不同的水平:


<Response>               //root

    <Business ... />     //level 1

    <Purchase... >       //level 1

        <Item ... />     // list

我的电话号码,姓名等都为空。


到目前为止,这是我尝试过的:


    [Serializable, XmlRoot("Response")]

    public class Response

    {

        public Depot depot = new Depot();


        // I have tried this also:

        //[XmlElement("Number")]

        //public string Number { get; set; }


        //[XmlElement("Name")]

        //public string Name { get; set; }

    }


    public class Depot

    {

        [XmlElement("Number")]

        public string Number { get; set; }


        [XmlElement("Name")]

        public string Name { get; set; }

    }



    static object DeserializeResponse(string responseString)

    {

        var serializer = new XmlSerializer(typeof(Response));


        Response result;

        using (var reader = new StringReader(responseString))

        {

            result = (Response)serializer.Deserialize(reader);

        }


        return result;

    }


喵喵时光机
浏览 163回答 1
1回答

慕姐4208626

我找到了解决方案:public class Response{&nbsp; &nbsp; [System.Xml.Serialization.XmlElementAttribute("Business", typeof(ResponseBusiness), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]&nbsp; &nbsp; public object[] Items { get; set; }}public partial class ResponseBusiness{&nbsp; &nbsp; string NumberField;&nbsp; &nbsp; string NameField;&nbsp; &nbsp; /// <remarks/>&nbsp; &nbsp; [System.Xml.Serialization.XmlAttributeAttribute()]&nbsp; &nbsp; public string Number&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this.NumberField;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; set&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.NumberField = value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; /// <remarks/>&nbsp; &nbsp; [System.Xml.Serialization.XmlAttributeAttribute()]&nbsp; &nbsp; public string Name&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this.NameField;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; set&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.NameField = value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }我这样称呼XmlSerializer类:var serializer = new XmlSerializer(typeof(Response), new XmlRootAttribute("Response"));我可以阅读以下信息:字符串businessNumber =(((ResponseBusiness)result.Items [0])。Number;希望它可以帮助别人。
打开App,查看更多内容
随时随地看视频慕课网APP