C# Foreach XML 节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2144962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:53:39  来源:igfitidea点击:

C# Foreach XML Node

c#xmlgridcoordinatesxmltextreader

提问by Gio Borje

I'm saving 2-dimensional coordinates on an XML file with a structure similar to:

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

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

I can open the XML file and read it via the XmlTextReader, but how do I loop through the coordinates specifically to retrieve both the time attribute and data between the initial and final nodes in some format similar to:

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

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


New Code:

新代码:

My New Code:

我的新代码:

//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++;
};

but now I get this error:
"Object reference not set to an instance of an object."

但现在我收到此错误:
“未将对象引用设置为对象的实例。”



XML

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>

Skipped a few coordinate tags to fit, but they all had the time attribute and initial/final subtags.

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



Globals

全局变量

uint counter = 0;

        // Coordinates to be retrieved from the XML file.
        string[][] coordinates;

采纳答案by marc_s

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

您可能想要检查类似 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....

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

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

有关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:

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

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??

这个列表和它的内容是什么样的??你得到你期望的所有坐标了吗?

回答by tyranid

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

您可以使用 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];
        }
    }     

Then in your code:

然后在你的代码中:

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