Parse Xml node of the same name
I have a problem when I try to parse this 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>
My program just read the first ActivateOnEquip, but I want it to read everything.
Here is my program:
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;
}
}
}
}
}
}
}
The console will just write Attack : 2
but I want it
Attack : 2
Defense : 2
Speed : 2
Vitality : 2
Wisdom : 2
Dexterity : 2
HP : 20
MP : 20
+3
source to share
1 answer
How about using 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);
}
+3
source to share