سؤال

I have a XML as below. I want to convert this to c# object . I tried modyfying but could not get it working.

<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>

I have a written a sample c# code and it doesn't work:

[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; }
}

And in the form:

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

Can someone suggest what am i doing wrong?

هل كانت مفيدة؟

المحلول

  1. SLVGeoZone-array is not a valid class name in C#

    [Serializable()]
    [XmlRoot("SLVGeoZone-array")]
    public class SLVGeoZones
    {
        [XmlElement("SLVGeoZone")]
        public SLVGeoZone[] Cars { get; set; }
    }
    
  2. XmlElement attribute values have to be exactly the same as element names in XML file. Yours are not.

    [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. What is CarCollection and why are you trying to deserialize your XML as CarCollection instead of classes you've shown here?

    XmlSerializer serializer = new XmlSerializer(typeof(SLVGeoZones));
    StreamReader reader = new StreamReader("Input.txt");
    var items = (SLVGeoZones)serializer.Deserialize(reader);
    reader.Close();
    
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top