3

I'm trying to deserialize an object in xml which is deeply nested.

Here's the xml code:

<modules>
    <channel>
      <resources>
        <resource name="x" refresh_interval="180">... text ...</resource>
        <resource name="y" refresh_interval="180">..text..</resource>
        <resource name="z" refresh_interval="180">... text ...</resource>
      </resources>
    </channel>
</modules>

I have a lot more elements like channel in the modules node, but for the example this one is enough I hope. Then I have my class:

    public class IdentifyData{

    public Modules modules;
}

public class Modules
{
     public List<Resources> channels;
}

    public class Resources
    {
        [DataMember(Name = "name")]
        public string name { get; set; }

        [DataMember(Name ="url")]
        public string url { get; set; }

        [DataMember(Name = "refresh_interval")]
        public string refresh_interval { get; set; }
    }

I tried with XmlArray and everything and it just doesn't want to work, and of course I searched all over stack overflow and I couldn't find the right answer.

dcreight
  • 641
  • 6
  • 18
Armin Lizde
  • 41
  • 1
  • 3

1 Answers1

2

If there aren't multiple modules within a response, and there aren't multiple images or channels in a module, then the following classes would work for you. You could further simplify this class structure with a base class that Image and Channel inherit from, and a couple of other attributes:

[Serializable]
[XmlRoot("response")]
public class IdentifyData
{
    [XmlElement("modules")]
    public Modules modules { get; set; }
}

[Serializable]
public class Modules
{
    [XmlElement]
    public Channel channel { get; set; }
    [XmlElement]
    public Image image { get; set; }
}
[Serializable]
public class Image
{
    [XmlArray("resources")]
    [XmlArrayItem("resource")]
    public List<Resources> resources { get; set; }

}

[Serializable]
public class Channel
{
    [XmlArray("resources")]
    [XmlArrayItem("resource")]
    public List<Resources> resources { get; set; }
}

[Serializable]
public class Resources
{
    [XmlAttribute]
    public string name { get; set; }

    [XmlAttribute]
    public string url { get; set; }

    [XmlAttribute]
    public string refresh_interval { get; set; }

    [XmlText]
    public string someText { get; set; }
}

Then deserialize it like this:

    using (var sr = new StreamReader("data.xml"))
    {
        var xs = new XmlSerializer(typeof(IdentifyData));
        var responseData = (IdentifyData)xs.Deserialize(sr);
        Console.WriteLine("Got {0} channel resources", responseData.modules.channel.resources.Count);
    }
denvercoder9
  • 801
  • 7
  • 15