noneJavaScript
noneJavaScript

Reputation: 845

How to deserialize nested XML?

I'm new into this, and I've been searching around similar questions and that's all I got for now. I want to keep XML hierarchy and make it a something that could be iterated.

static void Main(string[] args)
        {
            List<Movie> movies = DeserializeFromXML();
            for (int i = 0; i < movies.Count; i++)
            {
                Console.WriteLine(movies[i]);
            }
        }

.

static List<Movie> DeserializeFromXML()
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));
            TextReader textReader = new StreamReader(@"C:\movies.xml");

            List<Movie> movies;
            movies = (List<Movie>)deserializer.Deserialize(textReader);
            textReader.Close();

            return movies;
        }

.

public class Movie
{
  public string Name
  { get; set; }
}

.

<?xml version="1.0" encoding="utf-8"?>
<Favorites>
  <User>
    <Name>User 1 Name</Name>
    <Movie>
      <Name>Movie 1 Name</Name>
      <Actor>
        <Name>Actor Name</Name>
      </Actor>
      <Actor>
        <Name>Actor Name</Name>
      </Actor>
    </Movie>
    <Movie>
      <Name>Movie 2 Name</Name>
      <Actor>
        <Name>Actor Name</Name>
      </Actor>
    </Movie>
  </User>
    <User>
    <Name>User 2 Name</Name>
    <Movie>
      <Name>Movie 1 Name</Name>
      <Actor>
        <Name>Actor Name</Name>
      </Actor>
      <Actor>
        <Name>Actor Name</Name>
      </Actor>
    </Movie>
    <Movie>
      <Name>Movie 2 Name</Name>
      <Actor>
        <Name>Actor Name</Name>
      </Actor>
    </Movie>
  </User>
</Favorites>

My XML looks like that. This works and I can actually read the first level, but cant reach the lower levels yet.

Upvotes: 0

Views: 72

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156918

That is because you deserialize User into Movie, that is most likely the origin of your problem...

Your User class should contain a list of Movie. I would also recommend to fold the Movies into one XML list element since that makes deserializing easier.

Upvotes: 2

Related Questions