需要帮助清理我的XML解析器代码

时间:2014-10-06 11:37:49

标签: c# xml

所以,我试图熟悉XML。为此,我创建了一个简单的XML文件,之后我创建了一个C#脚本来读取该XML文件。现在一切都按预期工作,但代码感觉相当糟糕。

我的XML看起来像这样:

<buildings>
    <building>
        <name>House</name>
        <buildTime>5</buildTime>
        <treeCost>100</treeCost>
        <stoneCost>10</stoneCost>
        <goldCost>10</goldCost>
    </building>

    <building>
        <name>Tower</name>
        <buildTime>5</buildTime>
        <treeCost>10</treeCost>
        <stoneCost>300</stoneCost>
        <goldCost>50</goldCost>
    </building>
</buildings>

我的C#代码如下所示:

    XDocument xmlDoc = XDocument.Load ("BuildingGame_Data/Buildings.xml");

    var names = xmlDoc.Descendants("building").Descendants("name");
    var buildTimes = xmlDoc.Descendants("building").Descendants("buildTime");
    var treeCosts = xmlDoc.Descendants("building").Descendants("treeCost");
    var stoneCosts = xmlDoc.Descendants("building").Descendants("stoneCost");
    var goldCosts = xmlDoc.Descendants("building").Descendants("goldCost");

    List<string> namesList = new List<string>();
    List<int> buildTimesList = new List<int>();
    List<int> treeCostsList = new List<int>();
    List<int> stoneCostsList = new List<int>();
    List<int> goldCostsList = new List<int>();

    foreach (string n in names)
    {
        namesList.Add(n);
    }

    foreach (string b in buildTimes)
    {
        buildTimesList.Add(System.Convert.ToInt32(b));
    }

    foreach (string t in treeCosts)
    {
        treeCostsList.Add(System.Convert.ToInt32(t));
    }

    foreach (string s in stoneCosts)
    {
        stoneCostsList.Add(System.Convert.ToInt32(s));
    }

    foreach (string g in goldCosts)
    {
        goldCostsList.Add(System.Convert.ToInt32(g));
    }


    List<Building> buildings = new List<Building>();
    for (int i = 0; i < namesList.Count; i++)
    {
        buildings.Add(new Building(namesList[i], buildTimesList[i], treeCostsList[i], stoneCostsList[i], goldCostsList[i]));
    }

现在,我想要一种方法来跳过中间部分,我转换所有XML数据并将其存储在不同的列表中。这似乎是一个不必要的步骤,但我无法以任何其他方式使其工作。

1 个答案:

答案 0 :(得分:2)

一旦你有了你的后代,只需选择将xml映射到你的班级。您可以使用Element来获取&#34; building&#34;的子元素。并将它们投射到正确的值。

var buildings = xmlDoc.Descendants("building")
                      .Select(be => new Building (
                          (string)be.Element("name"),
                          (int)be.Element("buildTime"),
                          (int)be.Element("treeCost"),
                          (int)be.Element("stoneCost"),
                          (int)be.Element("goldCost")))
                      .ToList();