需要做些什么
目前,我有一个高级XML文件,需要解析。我需要迭代文件,并分别读取每个“实体”标记。我遇到的所有问题都是阅读&遍历统计数据和插槽。此外,根据实体的不同,Stat &槽标记的数量也会有所不同。(是的,我已经研究过这个话题了,但是我仍然找不到一条不制造错误的方法,因为我需要更多的指导。其他的帖子没有得到我所希望的确切的解决办法.)
XML文件
<ROOT>
<Entity Type="Clothing" Name="Light Robe" ID="0">
<Armor>2</Armor>
<Weight>1</Weight>
<Usability>120</Usability>
<Rarity>0.1</Rarity>
<Stats>
<Stat Type="Health">10</Stat>
</Stats>
<Slots>
<Slot>Torso</Slot>
</Slots>
</Entity>
<Entity Type="Clothing" Name="Medium Robe" ID="1">
<Armor>4</Armor>
<Weight>2</Weight>
<Stats>
<Stat Type="Health">15</Stat>
</Stats>
<Usability>120</Usability>
<Rarity>0.1</Rarity>
<Slots>
<Slot>Torso</Slot>
</Slots>
</Entity>
<Entity Type="Clothing" Name="Heavy Robe" ID="2">
<Armor>6</Armor>
<Weight>4</Weight>
<Stats>
<Stat Type="Health">25</Stat>
</Stats>
<Usability>120</Usability>
<Rarity>0.1</Rarity>
<Slots>
<Slot>Torso</Slot>
</Slots>
</Entity>
</ROOT>如果有人对这篇文章有任何批评,请说出来,我会相应地编辑。
发布于 2017-04-22 13:31:07
使用XDocument读取XML。
// Load Document
XDocument _doc = XDocument.Load("C:\\t\\My File2.txt");
// Get all Entity elements and put them into a list.
List<XElement> employees = _doc.XPathSelectElements("ROOT/Entity").ToList();
// Next you can loop thru the list to check the Entity's elements
foreach (var employee in employees)
{
// to get the armor element:
string armor = employee.Element("Armor").Value;
// to get the rarity element:
string rarity = employee.Element("Rarity").Value;
// to get the Stat element:
string stat = employee.Element("Stats").Element("Stat").Value;
// to get the Slot element:
string slot = employee.Element("Slots").Element("Slot").Value;
}
// To get one element specific by attribute use this (I check on attribute ID):
XElement emp = _doc.XPathSelectElements("ROOT/Entity").FirstOrDefault(c => c.Attribute("ID").Value == "0");
// Next you can extract information from this element just like in the foreach loop.https://stackoverflow.com/questions/43559755
复制相似问题