C#Foreach XML节点

Gio*_*rje 11 c# xml grid xmltextreader coordinates

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

<?xml version="1.0" encoding="utf-8" ?> 
<grid>
<coordinate time="78">
<initial>540:672</initial> 
<final>540:672</final> 
</coordinate>
</grid>
Run Code Online (Sandbox Code Playgroud)

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

string initial = "540:672";
string final  = "540:672";
int time = 78;
Run Code Online (Sandbox Code Playgroud)

新守则:

我的新代码:

//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++;
};
Run Code Online (Sandbox Code Playgroud)

但现在我收到此错误:
"对象引用未设置为对象的实例."


XML

<?xml version="1.0" encoding="utf-8"?>
<grid>
  <coordinate time="62">
    <initial>540:672</initial>
    <final>540:672</final>
  </coordinate>

  ...

  <coordinate time="46">
    <initial>176:605</initial>
    <final>181:617</final>
  </coordinate>
</grid>
Run Code Online (Sandbox Code Playgroud)

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


全局

uint counter = 0;

        // Coordinates to be retrieved from the XML file.
        string[][] coordinates;
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 25

您可能想要检查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
}
Run Code Online (Sandbox Code Playgroud)

这应该比使用直接的低级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; }
}
Run Code Online (Sandbox Code Playgroud)

并在您的主要代码中:

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
                                    });
Run Code Online (Sandbox Code Playgroud)

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

  • 借调.我现在尽可能使用XDocument/XElement,这样更容易. (3认同)