我有一個xml,我試圖通過LINQ查詢提取一些信息。
XML文件的格式如下所示:LINQ查詢來解析從XML到類的內容
<TopNode>
<Sample name="Tom" id="0" batch="1">
<Sequences>
<NextItem id="10">Stand1 ></NextItem>
<PreviousItem id="9">Stand2 ></PreviousItem>
</Sequences>
</Sample>
<Sample name="Hill" id="1" batch="1">
<Sequences>
<NextItem id="1">Stand1 ></NextItem>
<NextItem id="2">Stand3 ></NextItem>
<PreviousItem id="3">Stand4 ></PreviousItem>
</Sequences>
</Sample>
.
.
.
</TopNode>
我得既NextItem
和查詢PreviousItem
的屬性列表。爲此,我定義了一個類來獲得我的結果。
public class Extract
{
public string name
{
get;
set;
}
public int _id
{
get;
set;
}
}
LINQ查詢(的foreach樣本節點,獲得類對象的PreviousItem和NextItem內容):
var EnumerableContent = from item in XElement.Load("file.xml").Elements("NextItem")
select ???...
的問題是如何傳遞數據到類對象這裏在上面的查詢爲每個Sample節點。
。其次,以上只會給我NextItem節點。如何爲NextItem和PreviousItem編寫查詢?
編輯 整體上,我得一個IEnumerable每個每個Sequence
節點,然後從thie查詢返回的整體IEnumerable的。
EDIT2 指定key
這裏給我這個錯誤。下面
var mapping = XDocument.Load("file.xml")
.Descendants("Sequences")
.Select(n => n.Descendants("PreviousItem")
.Union(n.Descendants("NextItem"))
.Select(n1 => new Extract { _id = (int)n1.Attribute("id"), Name = n1.Value })
).ToDictionary<IEnumberable<Menu>, int>(key => key._id);//and further converting this dictionary to sorted dictionary (sorted accordign to keys)
這會給我IEnumerable的每個NextItem和PreviousItem。我真正想要的是,對於每個Sequence節點,我應該生成一個可枚舉,然後返回上面的整個IEnumberable。我希望我能夠轉達這個問題。 ; -/ – Cipher 2012-04-03 09:09:33
@Cipher我更新了答案,我希望我能正確理解你。 – 2012-04-03 09:25:21
謝謝!是的,但是我寫Extarct Class的原因是我想將結果轉換成一個字典,即'.ToDictionary',其中'TValue'可以是Extract類的IEnumberable。在上面的語句中,我無法執行'.Select(新菜單{SeekPoint =(int)n1.Attribute(「time」),ItemText = n1.Value})' –
Cipher
2012-04-03 09:58:03