C# Foreach XML Node

馋奶兔 提交于 2019-11-30 08:50:00
marc_s

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!