如何在c#中使用Linq to Xml中的几个级别

时间:2015-09-16 16:58:10

标签: c# xml linq

所以我在“root”元素中创建了一个包含多个级别的xml。基本上这就是它的外观:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Collectibles>
  <SaveAltars>
    <SaveAltar>
      <Location>
        <row>0</row>
        <col>1</col>
      </Location>
      <Quantity>1</Quantity>
      <Collected />
    </SaveAltar>
    <SaveAltar>
      <Location>
        <row>0</row>
        <col>3</col>
      </Location>
      <Quantity>1</Quantity>
      <Collected />
    </SaveAltar>
  <Fruits>
    <Fruit>
      <Location>
        <row>0</row>
        <col>1</col>
      </Location>
      <Quantity>7</Quantity>
      <Collected />
    </Fruit>
    <Fruit>
      <Location>
        <row>0</row>
        <col>4</col>
      </Location>
      <Quantity>4</Quantity>
      <Collected />
    </Fruit>
  </Fruits>
  <Lizards>
    <Lizard>
      <Location>
        <row>0</row>
        <col>1</col>
      </Location>
      <Quantity>1</Quantity>
      <Collected />
    </Lizard>
    <Lizard>
      <Location>
        <row>0</row>
        <col>3</col>
      </Location>
      <Quantity>1</Quantity>
      <Collected />
  </Lizards>
</Collectibles>

我也有像这样的简单类:

class Fruit
{
    public string Col;
    public string Row;
    public string Quantity;
    public string Collected;

}

我愿意使用linQ To Xml制作Fruits / Lizard / SaveAltars列表但我不知道你怎么去阅读收藏品列表的每个级别。就像阅读一个Fruit然后将它保存到一个classe并将其放入列表中一样。

我怎样才能实现这一目标?

现在我尝试了类似

的内容
    XDocument collectXml = XDocument.Load("collect.xml");
    foreach (XElement elem in collectXml.Descendants("Collectibles").Descendants("SaveAltars"))
    {
        MessageBox.Show(elem.Descendants("Location").Descendants("row").ToString());
    }

但它显示了一些随机代码,我不知道如何填充classe并将其保存在xml文件中每个元素的列表中:/

你可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

听起来你想要这样的东西:

var fruit = collectXml
    .Descendants("Fruit")
    .Select(x => new Fruit {
        Col = (string) x.Element("Location").Element("Col"),
        Row = (string) x.Element("Location").Element("Row"),
        Quantity = (string) x.Element("Quantity"),
        Collected = x.Element("Collected") == null ? "Yes" : "No"
    })
    .ToList();

正如评论中所述,您应该确实考虑使用更合适的类型 - 您可能需要Location类型的位置(int值为{{ 1}}和Row),Column intQuantity可能bool。哦,我强烈建议使用属性而不是公共字段。