【问题标题】:Deserialize XML to object doesn't work将 XML 反序列化为对象不起作用
【发布时间】:2014-02-17 03:54:40
【问题描述】:

我有一个如下的 XML。我想将其转换为 c# object 。我尝试修改但无法正常工作。

<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();

有人可以建议我做错了什么吗?

【问题讨论】:

  • “不起作用”是什么意思?它会抛出异常吗?它是否返回一个空对象?那些来自远古维度的难以言喻的恐怖扭曲?

标签: c# .net xml xml-serialization deserialization


【解决方案1】:
  1. SLVGeoZone-array 不是 C# 中的有效类名

    [Serializable()]
    [XmlRoot("SLVGeoZone-array")]
    public class SLVGeoZones
    {
        [XmlElement("SLVGeoZone")]
        public SLVGeoZone[] Cars { get; set; }
    }
    
  2. 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; }
    }
    
  3. CarCollection 是什么?为什么要将 XML 反序列化为 CarCollection 而不是此处显示的类?

    XmlSerializer serializer = new XmlSerializer(typeof(SLVGeoZones));
    StreamReader reader = new StreamReader("Input.txt");
    var items = (SLVGeoZones)serializer.Deserialize(reader);
    reader.Close();
    

【讨论】:

    猜你喜欢
    • 2017-10-06
    • 2020-05-10
    • 1970-01-01
    • 2012-09-18
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多