我有一个XML,如下所示。我想将其转换为c#对象。我试过modyfying但是无法让它运转起来。
<SLVGeoZone-array>
<SLVGeoZone>
<id>19</id>
<type>geozone</type>
<name>60_OLC_SC</name>
<namesPath>GeoZones/60_OLC_SC</namesPath>
<idsPath>1/19</idsPath>
<childrenCount>0</childrenCount>
</SLVGeoZone>
</SLVGeoZone-array>
我写了一个示例c#代码,它不起作用:
[Serializable]
public class SLVGeoZone
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement("type")]
public string type { get; set; }
[XmlElement("name")]
public string name { get; set; }
[XmlElement("namespath")]
public string namespath { get; set; }
[XmlElement("idspath")]
public string idspath { get; set; }
[XmlElement("childrencount")]
public string childrencount { get; set; }
}
[Serializable]
[XmlRoot("SLVGeoZone-array")]
public class SLVGeoZone-array
{
[XmlArray("SLVGeoZone-array")]
[XmlArrayItem("SLVGeoZone", typeof(SLVGeoZone))]
public SLVGeoZone[] Car { get; set; }
}
以表格形式:
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
有人可以建议我做错了吗?
答案 0 :(得分:1)
SLVGeoZone-array
不是C#
[Serializable()]
[XmlRoot("SLVGeoZone-array")]
public class SLVGeoZones
{
[XmlElement("SLVGeoZone")]
public SLVGeoZone[] Cars { get; set; }
}
XmlElement
属性值必须与XML文件中的元素名称完全相同。你的不是。
[Serializable()]
public class SLVGeoZone
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement("type")]
public string type { get; set; }
[XmlElement("name")]
public string name { get; set; }
[XmlElement("namesPath")]
public string namespath { get; set; }
[XmlElement("idsPath")]
public string idspath { get; set; }
[XmlElement("childrenCount")]
public string childrencount { get; set; }
}
什么是CarCollection
,为什么要将您的XML反序列化为CarCollection
而不是您在此处显示的类?
XmlSerializer serializer = new XmlSerializer(typeof(SLVGeoZones));
StreamReader reader = new StreamReader("Input.txt");
var items = (SLVGeoZones)serializer.Deserialize(reader);
reader.Close();