反序列化要列出的数组元素
本文关键字:数组元素 反序列化 | 更新日期: 2023-09-27 18:24:54
我有以下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。为什么?
让我们来解决这个问题。警告是一个"根"元素,因此,您也必须在类中转换它:
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));
[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>