让我说我有这个XML:
<items>
<item name="thumb">
<downloadStream>test1</downloadStream>
<downloadStream>test2</downloadStream>
<downloadStream>test3</downloadStream>
</item>
<item name="photo">
<downloadStream>test5</downloadStream>
<downloadStream>test6</downloadStream>
<downloadStream>test7</downloadStream>
</item>
</items>
我正在尝试编写一个LINQ语句,将其转换为以下字符串:
{ "thumb test1",
"thumb test2",
"thumb test3",
"photo test5",
"photo test6",
"photo test7", }
换句话说,它将父节点的属性附加到每个子节点的内部字符串。
他们是否可以使用一个LINQ查询来执行此类操作?我可以找到几种方法将其分解为多个步骤,但我感觉它们是一种更简单的方法。
谢谢!
答案 0 :(得分:1)
XDocument.Load(myXML)
.Descendants("item")
.SelectMany(d => d.Descendants()
.Select(ds => d.Attribute("name").Value + " " + ds.Value));
答案 1 :(得分:0)
var list = x.Descendants("item")
.SelectMany(item => item.Elements("downloadStream")
.Select(e => (string)item.Attribute("name")
+ " "
+ (string)e)).ToList();
答案 2 :(得分:0)
这是在VB.NET中。在C#中也可以做同样的事情,但我对VB语法更熟悉。
Dim itemsXml = <items>
<item name="thumb">
<downloadStream>test1</downloadStream>
<downloadStream>test2</downloadStream>
<downloadStream>test3</downloadStream>
</item>
<item name="photo">
<downloadStream>test5</downloadStream>
<downloadStream>test6</downloadStream>
<downloadStream>test7</downloadStream>
</item>
</items>
Dim itemQuery = From ds In itemsXml...<downloadStream> _
Select ds.Parent.@name & " " & ds.Value