Reading in XML file into 2D Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Drake250
    New Member
    • Dec 2009
    • 1

    Reading in XML file into 2D Array

    I've been trying to play around with reading in an XML file that would look something like this into a 2D array with no luck:
    Code:
    <?xml version="1.0" ?>
    <map index="0" name="Test" cellsx="2" cellsy="2" cellwidth="16" cellheight="16">
    	<layers>
    		<layer index="0" name="TopLayer" visible="1">
    			<cell x="0" y="0" img="24" />
    			<cell x="1" y="0" img="56" />
    			<cell x="0" y="1" img="23" />
    			<cell x="1" y="1" img="76" />
    		</layer>
    		<layer index="1" name="BottomLayer" visible="1">
    			<cell x="0" y="0" img="3" />
    			<cell x="1" y="0" img="3" />
    			<cell x="0" y="1" img="4" />
    			<cell x="1" y="1" img="4" />
    		</layer>
    	</layers>
    </map>
    I want to go through this XML document and put the data into a 2D array.
    So if the program went through it correctly there would be two 2D arrays of ints of size 2x2 with the number under img"#'. This would be similar to:
    Code:
    int [,] TopLayer = {
    {24,56},
    {23,76}
    };
    I've been reading many tutorials on using C#'s System.Xml to handle an XML file similar to this with no luck. Anyone else know how to do this, I thought it sounded simple but it has not been for me.

    Any help will be appreciated.
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    I don't know what you were looking at for XML tutorials, but look into the XmlDocument and XmlNode classes. You can read that entire block of XML into an XmlDocument object, then get the root node. After that, it's a hierarchical representation of the nodes, and fairly simple to parse using a foreach loop.

    Some pseudo code to get you started, perhaps?

    Code:
    for every node in the root node
    {
      if node is layers (ie, node.Name)
      {
        for every node in the layers node
        {
          if node is a layer node
          {
            read size data
            instantiate a container object
            for each node in the layer node
            {
              if node is a cell node
              {
                fill object with node data
              }
            }
          }
        }
      }
    }
    That should be a rough map of what you want to do, MSDN will help you find the specifics of syntax :)

    Comment

    Working...