andryuha
andryuha

Reputation: 1606

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

Upvotes: 0

Views: 1708

Answers (3)

Kevin Hsu
Kevin Hsu

Reputation: 1756

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

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160852

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

Upvotes: 1

Bala R
Bala R

Reputation: 108937

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

Upvotes: 2

Related Questions