如何使用linq和xml数据显示所有树子节点?

时间:2011-04-26 10:08:15

标签: linq-to-xml

这是我的xml文件。我想使用linq.can显示所有子节点,是否有人给我建议或回答?

                                                                                                             

1 个答案:

答案 0 :(得分:0)

这将打印出每个块及其所有字段:

var tree = XElement.Parse(text);
foreach(var farm in tree.Descendants("farm"))
{
    Console.WriteLine(farm.Attribute("Name").Value);
    // print the blocks and their fields
    foreach(var block in farm.Descendants("block"))
    {
        Console.WriteLine("\t{0}", block.Attribute("Name").Value);
        foreach(var field in block.Descendants("field"))
            Console.WriteLine("\t\t{0}", field.Attribute("Name").Value);
    }
    // print out the remaining fields that don't belong to a block
    foreach(var field in farm.Descendants("field"))
    {
        Console.WriteLine("\t{0}", field.Attribute("Name").Value);
    }
}
像这样:

Farm A
  Field 1
Farm B
  Block North
    Field 11
    Field 12
  Block South
    Field 25
    Field 26
    Field 27
    Field 28
  Field 11
  Field 12
  Field 25
  Field 26
  Field 27
  Field 28