这是我输入的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<hosts>
<host>
<hostId>239|BS|OWN</hostId>
<images>
<image>
<name>Pic.jpg</name>
<main>true</main>
<source>../Images/Melissa/Pic.jpg</source>
</image>
</images>
</host>
</hosts>
这是我用来解除XML文件的类:
[XmlRoot("hosts")]
public class hosts
{
[XmlElement("host")]
public List<Host> Listehosts { get; set; }
}
public class Host
{
[XmlElement("hostId")]
public string hostId { get; set; }
[XmlElement("images")]
public List<Image> Listeimages { get; set; }
}
public class Image
{
[XmlElement("name")]
public string name { get; set; }
[XmlElement("main")]
public string main { get; set; }
[XmlElement("source")]
public string source { get; set; }
}
这是我主程序的代码:
string outputTmp = "Images.xml";
XmlSerializer deserializer = new XmlSerializer(typeof(hosts));
TextReader reader = new StreamReader(outputTmp);
object obj = deserializer.Deserialize(reader);
hosts XmlData = (hosts)obj;
reader.Close();
Console.WriteLine(XmlData.Listehosts.Count);
问题是当我执行程序时,图像列表总是空的。
主机列表已正确收费但当我检查图片列表时,它包含所有属性(name
,main
,source
)的永久空值。
我错过了什么吗?
答案 0 :(得分:1)
试试这个:
public class Host
{
[XmlElement("hostId")]
public string hostId { get; set; }
[XmlArray("images")] // CHANGED
[XmlArrayItem("image", typeof(Image))] // CHANGED
public List<Image> Listeimages { get; set; }
}
答案 1 :(得分:0)
您的代码中存在一个小错误,添加一个带有列表的ImageCollection类。
public class ImageCollection
{
[XmlElement("image")]
public List<Image> Listeimages { get; set; }
}
public class Host
{
[XmlElement("hostId")]
public string hostId { get; set; }
[XmlElement("images")]
public ImageCollection ImageCollection { get; set; }
}