1

I'm newbie in serialization and I'm trying to deal with this problem: I have this xml file

<Database>
<Castle>
    <Tower>
        <Roof>
            <Color>red</Color>
        </Roof>
        <Roof>
            <Color>blue</Color>
        </Roof>
        <Roof>
            <Color>pink</Color>
        </Roof>
    </Tower>
    <Tower>
        <Roof>
            <Color>green</Color>
        </Roof>
        <Roof>
            <Color>black</Color>
        </Roof>
    </Tower>
</Castle>

And I'm trying to get data from my xml file and put it in to my classes structure that looks like like this:

class Castle{ // I want this to fill with tower[0] and tower[1]
    public Towers[] tower;  
}

class Towers{ // I want this to fill with tower[0].roof[0], tower[0].roof[1], tower[0].roof[2] and tower[1].roof[0], tower[1].roof[1]
    public Roofs[] roof;  
}

class Roofs{ // And finally I want to be able co call tower[1].roof[1] and get variable "black"
    public string color;
}

for this purpose I'm using this function:

public static Castle Load(string path)
{
    var serializer = new XmlSerializer(typeof(Castle));
    using(var stream = new FileStream(path, FileMode.Open))
    {
        return serializer.Deserialize(stream) as Castle;
    }
}

My problem is, that I'm unable to properly set up XmlArray and XmlArrayItem to get data from my xml. can you please give me some advice how to solve my problem?

MrIncognito
  • 153
  • 12

1 Answers1

1

Use annotations to get the exact node names in the xml:

 [Serializable]
public class Castle
{ 
    [XmlElement("Tower")]
    public Towers[] tower;
}

public class Towers
{ 
    [XmlElement("Roof")]
    public Roofs[] roof;
}

public class Roofs
{ 
    [XmlElement("Color")]
    public string color;
}

this works fine for me when I remove the initial [Database] node from your xml, as it was making the xml invalid.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112