Search code examples
c#androidxmlserializationxstream

Deserialize an XML in C# generated by XStream from java


My application has 2 parts, an android client and a windows print server coded in c#.

I used Xstream in java to convert my object to XML (in android). here's a part of it:

<ROOT>
  <id>1</id>
  <serial>92000</serial>
  <date>2013/2/15</date>

  <ITEMS>

    <ITEM>
      <name>/**SOMETHING**/</name>
      <idd>/**SOMETHING**/</idd>
      <pd>/**SOMETHING**/</pd>
      <ed>/**SOMETHING**/</ed>
    </ITEM>
    <ITEM>
      <name>/**SOMETHING**/</name>
      <idd>/**SOMETHING**/</idd>
      <pd>/**SOMETHING**/</pd>
      <ed>/**SOMETHING**/</ed>
    </ITEM>
    <ITEM>
      <name>/**SOMETHING**/</name>
      <idd>/**SOMETHING**/</idd>
      <pd>/**SOMETHING**/</pd>
      <ed>/**SOMETHING**/</ed>
    </ITEM>

  </ITEMS>

</ROOT>

as you can see, I have 2 object types, one ROOT object type, and a nested list of second object type named ITEMS. I can read the ROOT object's name,serial and date, but for the nested list of ITEMS object, it always return null.

the class for the Root class in c# is:

[XmlRoot("ROOT")]
    public class ROOT_CLASS
    {

        [XmlElement("id")]
        public string idVar{ get; set; }

        [XmlElement("serial")]
        public string serialVar{ get; set; }

        [XmlElement("date")]
        public string dateVar{ get; set; }

        [XmlArray("ITEMS")]
        [XmlArrayItem("ITEM")]
    public List<NESTED_CLASS> oi { get; set; }

    }

and here is the nested object class:

[XmlRoot("ITEM")]
    public class NESTED_CLASS
    {
        [XmlElement("name")]
        public string nameVV; { get; set; }
        [XmlElement("idd")]
        public string iddVV; { get; set; }
        [XmlElement("pd")]
        public string pdVV; { get; set; }
        [XmlElement("ed")]
        public string edVV; { get; set; }

    } 

okay, How can I deserialize the NESTED_CLASS list out of this xml? as I said, I always get a null out of it. please help me. thanks...


Solution

  • Use XmlArray attribute

    [XmlRoot(ElementName = "ROOT")]
    public class Root
    {
        public int id { get; set; }
        public int serial { get; set; }
        public string date { get; set; }
    
        [XmlArray(ElementName = "ITEMS")]
        [XmlArrayItem("ITEM")]
        public List<RootItem> Items { get; set; }
    }
    
    public class RootItem
    {
        public string name { get; set; }
        public string idd { get; set; }
        public string pd { get; set; }
        public string ed { get; set; }
    }