C#Foreach XML节点

我在XML文件上保存二维坐标,其结构类似于:

   540:672 540:672   

我可以打开XML文件并通过XmlTextReader读取它,但是我如何专门遍历坐标以检索初始节点和最终节点之间的时间属性和数据,格式类似于:

 string initial = "540:672"; string final = "540:672"; int time = 78; 

新代码:

我的新代码:

 //Read the XML file. XDocument xmlDoc = XDocument.Load("C:\\test.xml"); foreach (var coordinate in xmlDoc.Descendants("coordinate")) { this.coordinates[this.counter][0] = coordinate.Attribute("time").Value; this.coordinates[this.counter][1] = coordinate.Element("initial").Value; this.coordinates[this.counter][2] = coordinate.Element("final").Value; this.counter++; }; 

但现在我收到这个错误:
“你调用的对象是空的。”


XML

    540:672 540:672  ...  176:605 181:617   

跳过一些坐标标签以适应,但它们都有时间属性和初始/最终子标签。


全局

 uint counter = 0; // Coordinates to be retrieved from the XML file. string[][] coordinates; 

您可能想要检查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 } 

这应该比使用直接的低级XmlTextReader容易得多….

有关Linq-to-XML的介绍,请参阅此处或此处 (或许多其他地方)。


更新:

请尝试此代码 – 如果它有效,并且您获得了结果列表中的所有坐标,那么Linq-to-XML代码就可以了:

定义一个新的帮助器类:

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

并在您的主要代码中:

 XDocument xdoc = XDocument.Load("C:\\test.xml"); IEnumerable 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 }); 

这个列表及其内容如何? 你得到了你所期望的所有坐标吗?

您可以使用XmlSerialization将XML转换为具有少量工作的简单坐标类列表,例如

  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]; } } 

然后在你的代码中:

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