解析高级XML文件&在C#中将信息转换为类

时间:2017-04-22 13:23:24

标签: c# xml

需要做什么

目前,我有1个高级 XML 文件,需要解析。我需要遍历文件并分别读取每个“Entity”标记。至于我遇到的问题是阅读&迭代统计和插槽。此外,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>

如果有人对此帖有任何批评,请说明,我会相应地进行编辑。

1 个答案:

答案 0 :(得分:0)

使用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.