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

时间:2018-05-01 00:53:49

标签: c# xmlserializer

如何将此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;
    }

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

public class Response
{
    [System.Xml.Serialization.XmlElementAttribute("Business", typeof(ResponseBusiness), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public object[] Items { get; set; }
}

public partial class ResponseBusiness
{
    string NumberField;

    string NameField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Number
    {
        get
        {
            return this.NumberField;
        }
        set
        {
            this.NumberField = value;
        }
    }
    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name
    {
        get
        {
            return this.NameField;
        }
        set
        {
            this.NameField = value;
        }
    }

我像这样调用XmlSerializer类:

var serializer = new XmlSerializer(typeof(Response), new XmlRootAttribute("Response"));

我可以阅读这样的信息:

string businessNumber =((ResponseBusiness)result.Items [0])。Number;

希望它可以帮助别人。