简体   繁体   中英

best way to deserialize xml in c#?

I have following xml:

<return_obj from_call_to="categories">
  <categories>
    <category>
      <value>12341234</value>
      <label>First</label>
    </category>
    <category>
      <value>242234234</value>
      <label>Another</label>
    </category>
  </categories>
</return_obj>

so marked up an object to serialize this into

[XmlRoot(ElementName = "return_obj")]
public class returnobject
{
    [XmlElement]
    public category[] categories { get; set; }
}

public class category
{
    [XmlElement]
    public string value { get; set; }
    [XmlElement]
    public string label { get; set; }
}

and tried using this to do it

    var ser = new XmlSerializer(typeof (returnobject));
    var obj = (returnobject)ser.Deserialize(File.OpenRead("test.xml"));

However, the categories collection always some ups null.

What am I doing wrong? Is there a better way?

Thanks

Make categories field public in class returnobject . That would help.

XmlSerializer only looks at public fields and properties, so you have to make categories public in your returnobject class.

Also you have to specify the name of the XML array container you want to use, in your case categories - this worked for me:

[XmlRoot(ElementName = "return_obj")]
public class returnobject
{
    [XmlArray("categories")]
    [XmlArrayItem("category")]
    public category[] categories { get; set; }
}

FYI, XmlSerializer has to generate type information of the serialization types. This can take a while, so you might find serialization and deserialization taking several hundred milliseconds. You can get around this by running SGEN to pre-generate the serialization assemblies.

Alternatively, you can use XmlReader to read the XML and just code the serialization yourself. It's more code, but always performs well and isn't burdened with the extra assembly (generated or not).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM