C#获取XElement的所有子项,无论它们的值如何

时间:2014-10-14 10:56:31

标签: c# xml linq

我有以下XML结构:

<init_deinit>
    <step name="init">
        <call>...</call>
        <check>...</check>
        <call>...</call>
        <wait>...</wait>
        ....
    </step>
    <step name="deinit">
        ....
    </step>
</init_deinit>

有很多关于如何检索单个类型的所有后代的示例。即:

XDocument xdoc = XDocument.Load("file.xml")
var all_call_tags = xdoc.Descendants("init_deinit").Elements("step").ElementAt(0).Elements("call");

但我需要检索“步骤”中的所有孩子。我需要按照XML编写的确切顺序检索它们。所以我需要的是IEnumerable迭代器,它包含XElements调用,检查,调用和按此顺序等待。我试过但到目前为止失败了:))

感谢您的建议!

2 个答案:

答案 0 :(得分:2)

这将为您提供所有Descendantsstep元素:

xdoc.Descendants("step").SelectMany(x => x.Descendants());

如果您希望使用Descendants元素step

xdoc.Descendants("step").First().Descendants();

答案 1 :(得分:1)

请试试这个:

XDocument xdoc = XDocument.Load("file.xml");

//Here you will get all the descendants of the first step 
xdoc.Descendants("step").First().Descendants();

//To get all Descendants of step elements:
var x = xdoc.Descendants("step").Descendants();
相关问题