C# Foreach XML 节点

发布于 2024-08-19 11:15:24 字数 1513 浏览 10 评论 0原文

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

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

我可以打开 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

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

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


全局变量

uint counter = 0;

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

演出会有结束 2024-08-26 11:15:24

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

并在您的 main 中代码:

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.Element("initial").Value,
                                      Final = x.Element("final").Value
                                    });

这个列表及其内容是什么样的?你得到了你想要的所有坐标吗?

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.Element("initial").Value,
                                      Final = x.Element("final").Value
                                    });

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

年少掌心 2024-08-26 11:15:24

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文