XDocument xDoc = XDocument.Load(myXml); //load your XML from file or stream
var rows = xDoc.Descendants("item").Select(x => string.Format(
@"\{0}-{1}\{2}-{3}",
x.Ancestors("itemGroup").First().Attribute("description").Value,
x.Ancestors("itemGroup").First().Attribute("label").Value,
x.Attribute("label").Value,
x.Attribute("description").Value));
让我们来分解一下我们正在做的事情:
-
xDoc.Descendants("item")
得到我们所有
<item>
整个文档中的元素
-
Select(x => string.Format(format, args)
项目
每个
<项目& GT;
我们从上一个操作得到了lambda中指定的任何格式。在这种情况下,A
formatted string
.
-
就XML树而言,我们“坐在”了
<项目& GT;
级别,因此我们需要回滚树以使用
Ancestors
. 因为这个方法返回一系列元素,所以我们知道我们需要第一个(离我们最近的),这样我们就可以读取它的属性。
现在你有了
IEnumerable<string>
一个
<项目& GT;
在XML文档和指定格式的信息中:
foreach(string row in rows)
{
Console.WriteLine(row);
}