反序列化数组数组

时间:2015-10-19 20:05:24

标签: c# xml deserialization

我是序列化的新手,我正在尝试解决这个问题: 我有这个xml文件

assert

我正在尝试从我的xml文件中获取数据并将其放入我的类结构中,如下所示:

<Database>
<Castle>
    <Tower>
        <Roof>
            <Color>red</Color>
        </Roof>
        <Roof>
            <Color>blue</Color>
        </Roof>
        <Roof>
            <Color>pink</Color>
        </Roof>
    </Tower>
    <Tower>
        <Roof>
            <Color>green</Color>
        </Roof>
        <Roof>
            <Color>black</Color>
        </Roof>
    </Tower>
</Castle>

为此我正在使用这个功能:

class Castle{ // I want this to fill with tower[0] and tower[1]
    public Towers[] tower;  
}

class Towers{ // I want this to fill with tower[0].roof[0], tower[0].roof[1], tower[0].roof[2] and tower[1].roof[0], tower[1].roof[1]
    public Roofs[] roof;  
}

class Roofs{ // And finally I want to be able co call tower[1].roof[1] and get variable "black"
    public string color;
}

我的问题是,我无法正确设置XmlArray和XmlArrayItem来从我的xml中获取数据。能不能给我一些建议如何解决我的问题?

1 个答案:

答案 0 :(得分:1)

使用注释在xml中获取完全节点名称:

 [Serializable]
public class Castle
{ 
    [XmlElement("Tower")]
    public Towers[] tower;
}

public class Towers
{ 
    [XmlElement("Roof")]
    public Roofs[] roof;
}

public class Roofs
{ 
    [XmlElement("Color")]
    public string color;
}

当我从xml中删除初始[Database]节点时,这对我来说很好,因为它使xml无效。