如何反序列化XML字符串 [英] How to deserialize an xml string

查看:190
本文介绍了如何反序列化XML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图反序列化的XML字符串,我没有得到反序列化对象。

I was trying to deserialize an xml string and I am not getting deserialized the objects.

我的XML字符串的样子

My xml string looks like

<Cars>
    <Car>
        <Id>123445</Id>
        <BMW>
          <Id>78945</Id>
        </BMW>
    </Car>
</Cars>

[Serializable()]
[XmlRoot("Cars")]
public class Cars
{
    [XmlArrayItem("Car",typeof(Car))]
    public Car[] Car { get; set; }
}

[Serializable()]
public class Car
{
    [XmlElement("Id")]
    public long Id { get; set; }

    [XmlArrayItem("BMW",typeof(BMW))]
    public BMW[] BMW { get; set; }
}

[Serializable()]
public class BMW
{
    [XmlElement("Id")]
    public long Id { get; set; }
}

这是code我想:

And this is the code I am trying:

string str = "xml string like above";
XmlSerializer ser = new XmlSerializer(typeof(Cars));
var wrapper = (Cars) ser.Deserialize(new StringReader(str));

和我确实有几个子阵列的对象里面像宝马里面。但它不是序列化汽车。 是否有人可以在这里指出我的错误?

And I do have couple of sub array objects inside like BMW inside. BUt it is not serializing Car. Can someone please point out my mistake here?

推荐答案

尝试使用的XmlElement 而不是 XmlArrayItem 自该项目没有封装标签:

Try using XmlElement instead of XmlArrayItem since the items have no encapsulation tag:

[Serializable()]
[XmlRoot("Cars")]
public class Cars
{
    [XmlElement("Car",typeof(Car))]
    public Car[] Car { get; set; }
}

[Serializable()]
public class Car
{
    [XmlElement("Id")]
    public long Id { get; set; }

    [XmlElement("BMW",typeof(BMW))]
    public BMW[] BMW { get; set; }
}

这篇关于如何反序列化XML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆