解析同名的 Xml 节点
Posted
技术标签:
【中文标题】解析同名的 Xml 节点【英文标题】:Parse Xml node with same name 【发布时间】:2015-10-05 23:13:30 【问题描述】:当我尝试解析这个 xml 时遇到问题
<?xml version="1.0" encoding="ISO-8859-1"?>
<Objects>
<Object type="0x141" id="Amulet of Resurrection">
<Class>Equipment</Class>
<Item />
<ActivateOnEquip stat="20" amount="2">IncrementStat</ActivateOnEquip>
<ActivateOnEquip stat="21" amount="2">IncrementStat</ActivateOnEquip>
<ActivateOnEquip stat="22" amount="2">IncrementStat</ActivateOnEquip>
<ActivateOnEquip stat="26" amount="2">IncrementStat</ActivateOnEquip>
<ActivateOnEquip stat="27" amount="2">IncrementStat</ActivateOnEquip>
<ActivateOnEquip stat="28" amount="2">IncrementStat</ActivateOnEquip>
<ActivateOnEquip stat="0" amount="20">IncrementStat</ActivateOnEquip>
<ActivateOnEquip stat="3" amount="20">IncrementStat</ActivateOnEquip>
</Object>
</Objects>
我的程序刚刚读取了第一个 ActivateOnEquip,但我希望它读取所有内容。
这是我的程序:
using System;
using System.Xml;
namespace ParseXML
internal class Program
private static void Main(string[] args)
ParseXMLEquip(@"..\..\obj\Debug\Object\Test.xml");
Console.ReadLine();
private static void ParseXMLEquip(string fileName)
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
XmlNodeList EquipNodes = xmlDocument.SelectNodes("//*");
foreach (XmlNode EquipNode in EquipNodes)
XmlNode Stat = EquipNode["ActivateOnEquip"];
if (Stat != null)
switch (Stat.Attributes["stat"].InnerText)
case "0":
Console.WriteLine("Hp: " + Stat.Attributes["amount"].InnerText);
break;
case "3":
Console.WriteLine("Mp: " + Stat.Attributes["amount"].InnerText);
break;
case "20":
Console.WriteLine("Attack: " + Stat.Attributes["amount"].InnerText);
break;
case "21":
Console.WriteLine("Defense: " + Stat.Attributes["amount"].InnerText);
break;
case "22":
Console.WriteLine("Speed: " + Stat.Attributes["amount"].InnerText);
break;
case "28":
Console.WriteLine("Dexterity: " + Stat.Attributes["amount"].InnerText);
break;
case "26":
Console.WriteLine("Vitality: " + Stat.Attributes["amount"].InnerText);
break;
case "27":
Console.WriteLine("Wisdom: " + Stat.Attributes["amount"].InnerText);
break;
控制台只写Attack : 2
但我想要这个
Attack : 2
Defense : 2
Speed : 2
Vitality : 2
Wisdom : 2
Dexterity : 2
HP : 20
MP : 20
【问题讨论】:
【参考方案1】:使用 Linq2Xml 怎么样
Dictionary<string, string> mapping = new Dictionary<string, string>()
"0","Hp",
"3","Mp",
"20","Attack",
"21","Defence",
"22","Speed",
"28","Dexterity",
"26","Vitality",
"27","Wisdom",
;
var result = XDocument.Load(filename)
.Descendants("ActivateOnEquip")
.Select(x => new stat = x.Attribute("stat").Value, amount = x.Attribute("amount").Value )
.ToList();
foreach(var item in result)
Console.WriteLine( mapping[item.stat] + ": " + item.amount);
【讨论】:
我可以在此代码中添加类似元素以上是关于解析同名的 Xml 节点的主要内容,如果未能解决你的问题,请参考以下文章