反序列化要列出的数组元素

时间:2012-02-16 11:21:17

标签: c# xml-serialization

我有以下XML ...

<configuration>
    <img name="name1" />
    <img name="name2" />
    <warn>
        <img name="warn1" />
    </warn>
</configuration>

...我尝试将其反序列化为...

[XmlType("img")]
public class ImageNameExceptionItemXml
{
    [XmlAttribute("name")]
    public string Filename;
}

[XmlRoot("configuration")]
public class ImageNameExceptionListXml: List<ImageNameExceptionItemXml>
{
    [XmlArray("warn")]
    [XmlArrayItem("img")]
    public ImageNameExceptionListXml WarnList { get; set; }
}

...但最终WarnList属性为null。

我已经尝试过......

[XmlElement("warn"}]
public ImageNameExceptionListXml WarnList { get; set; }

...或...

[XmlElement("warn"}]
public List<ImageNameExceptionItemXml> WarnList { get; set; }

...但我仍然以WarnList属性null结束。那是为什么?

2 个答案:

答案 0 :(得分:4)

让我们来解决问题。警告是一个&#34; root&#34;元素,所以,你必须在类中转换它:

xml:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <img name="name1" />
  <img name="name2" />
  <warn>
      <img name="warn1" />
      <img name="warn2" />
  </warn>
</configuration>

班级:

[XmlType("img")]
public class ImageNameExceptionItemXml 
{ 
    [XmlAttribute("name")]     
    public string Filename; 
}

[XmlType("warn")]
public class WarnExceptionItemXml
{
    [XmlElement("img")]
    public List<ImageNameExceptionItemXml> ImgList { get; set; }
}

[XmlRoot("configuration")]
public class ImageNameExceptionListXml
{
    [XmlElement("img")]
    public List<ImageNameExceptionItemXml> ImgList { get; set; }

    [XmlElement("warn")]
    public WarnExceptionItemXml WarnList { get; set; } 
}

反序列化测试:

XmlSerializer xml = new XmlSerializer(typeof(ImageNameExceptionListXml));

ImageNameExceptionListXml teste = (ImageNameExceptionListXml)xml.Deserialize(new FileStream("XMLFile1.xml", FileMode.Open));

答案 1 :(得分:0)

XmlSerializer只允许数组/列表中的一种类型。很好。发布我的测试代码:

[XmlType("img")]
[Serializable]
public class ImageNameExceptionItemXml
{
    [XmlAttribute("name")]
    public string Filename;
}

[XmlType("warn")]
[Serializable]
public class Warnning
{
    [XmlArrayItem(typeof(ImageNameExceptionItemXml))]
    public List<ImageNameExceptionItemXml> imgs { get; set; }
}

[XmlRoot("configuration")]
[Serializable]
public class ImageNameExceptionListXml
{
    [XmlArrayItem(typeof(Warnning))]
    public List<Warnning> warns{ get; set; }

    [XmlArrayItem(typeof(ImageNameExceptionItemXml))]
    public List<ImageNameExceptionItemXml> imgs { get; set; }

}

的xml:

<configuration>
<imgs>
    <img name="name1" />
    <img name="name2" />
</imgs>
<warns>
    <warn>
      <imgs>
        <img name="warn2" />
        <img name="warn1" />
      </imgs>
    </warn>
    <warn>
      <imgs>
        <img name="warn3" />
        <img name="warn4" />
      </imgs>
    </warn>
 </warns>
</configuration>