C# Foreach XML Node C# Foreach XML Node xml xml

C# Foreach XML Node


You might want to check into something like Linq-to-XML:

XDocument coordinates = XDocument.Load("yourfilename.xml");foreach(var coordinate in coordinates.Descendants("coordinate")){    string time = coordinate.Attribute("time").Value;    string initial = coordinate.Element("initial").Value;    string final = coordinate.Element("final").Value;    // do whatever you want to do with those items of information now}

That should be a lot easier than using straight low-level XmlTextReader....

See here or here (or a great many other places) for introductions to Linq-to-XML.


UPDATE:

please try this code - if it works, and you get all the coordinates in that resulting list, then the Linq-to-XML code is fine:

Define a new helper class:

public class Coordinate{    public string Time { get; set; }    public string Initial { get; set; }    public string Final { get; set; }}

and in your main code:

XDocument xdoc = XDocument.Load("C:\\test.xml");IEnumerable<XElement> cords= xdoc.Descendants("coordinate");var coordinates = cords                  .Select(x => new Coordinate()                                   {                                      Time = x.Attribute("time").Value,                                      Initial = x.Attribute("initial").Value,                                      Final = x.Attribute("final").Value                                    });

How does this list and its contents look like?? Do you get all the coordinates you're expecting??


You could have used XmlSerialization to make the XML into a simple list of coordinate classes with a small amount of work, e.g.

    public class coordinate    {        [XmlAttribute]        public int time;        [XmlElement(ElementName="initial")]        public string initial;        [XmlElement(ElementName = "final")]        public string final;        public coordinate()        {            time = 0;            initial = "";            final = "";        }    }    public class grid    {        [XmlElement(ElementName="coordinate", Type = typeof(coordinate))]        public coordinate[] list;        public grid()        {            list = new coordinate[0];        }    }     

Then in your code:

XmlReader r = new XmlReader.Create(...);grid g = (grid) new XmlSerializer(typeof(grid)).Deserialize(r);