简体   繁体   English

XML / C#遍历同名节点

[英]XML / C# Loop through nodes of the same name

I have this XML file with keys and values, and I currently loop through the XML doc, and I read all the data. 我有一个包含键和值的XML文件,并且当前正在遍历XML文档,并且读取了所有数据。

However, I have certain 'keys' or 'Nodes' that have the same keyname, but different (or same) values. 但是,我有某些具有相同键名但值不同(或相同)的“键”或“节点”。 I need to loop through these same nodes within the same parent node. 我需要遍历同一父节点内的这些相同节点。

<tile>
   <x>0</x>
   <y>1</y>
   <name>Grass</name>
   <entity>Tree</entity>
   <entity>Building</entity>
   <entity>Something</entity>
</tile>
<tile>
   <x>1</x>
   <y>2</y>
   <name>Dirt</name>
   <entity>Tree</entity>
   <entity>Building</entity>
</tile> 

I need to get X, Y and the Name, and an array/list of the entity. 我需要获取X,Y和名称,以及实体的数组/列表。 This I need for every Tile in the XML. 我需要XML中的每个Tile。

So I need to loop through all of the and get the contents, including a list with the 因此,我需要遍历所有并获取内容,包括带有

Current code: 当前代码:

        XmlElement element = doc.DocumentElement;
        XmlNodeList nList = element.SelectNodes("/map/tile");
        foreach(XmlNode node in nList){
            int x = int.Parse(node["x"].InnerText);
            int y = int.Parse(node["y"].InnerText);
            String materialName = node["name"].InnerText;
            for(node["entity"] in allEntityNodesWithinThisTile){ }
        }

Thanks 谢谢

string xml = @"<tile>
   <x>0</x>
   <y>1</y>
   <name>Grass</name>
   <entity>Tree</entity>
   <entity>Building</entity>
   <entity>Something</entity>
</tile>";

var data = from t in XElement.Parse(xml).DescendantsAndSelf("tile")
select new {
   X=(int)t.Element("x"),
   Y=(int)t.Element("y"),
   Name=(string)t.Element("name"),
   Entities= t.Elements("entity").Select (x => x.Value)
};
var data = from t in XElement.Load(xmlFileName).DescendantsAndSelf("tile")
select new {
   X=(int)t.Element("x"),
   Y=(int)t.Element("y"),
   Name=(string)t.Element("name"),
   Entities= t.Elements("entity").Select (x => x.Value)
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM