我有一個看起來像這樣的XML文件:的LINQ to XML子查詢到列表框
<?xml version="1.0" encoding="utf-8" ?>
<scripts>
<script id="1">
<name>A Script File</name>
<author>Joe Doe</author>
<fileDestination>
<destination>W:\folderolder\</destination>
<destination>W:\anotherfolder\</destination>
<destination>W:\athirdfolder\</destination>
</fileDestination>
</script>
<script id="2">
<name>Another File</name>
<author>Bobby Doe</author>
<fileDestination>
<destination>W:\somefolder\</destination>
<destination>W:\someotherfolder\</destination>
</fileDestination>
</script>
</scripts>
我有一個LINQ到了我與此SO Question一些幫助制定了XML查詢。
var query3 = (from c in xDoc.Descendants("script")
select new
{
Name = (string)c.Element("name").Value,
Author = (string)c.Element("author").Value,
//Destination = c.Element("fileDestination").Elements().Select(e => (string)c.Element("destination").Value)
//Destination = c.Element("fileDestination").Elements().Where(e => (string)c.Element("destination").Value != null).Select(e => (string)c.Element("destination").Value).ToList()
Destination = c.Descendants("fileDestination").Elements().Where(e => c.Element("fileDestination").Element("destination").Value != null).Select(e => (string)c.Element("destination").Value)
});
麻煩的是,(1)我總是得到nullreferenceerror和(2)我不知道如何訪問第二選擇的結果。我可以這樣做:
txtScriptTitle.Text = query.FirstOrDefault().Name;
cmboAuthor.Text = query.FirstOrDefault().Author;
顯示前兩個項目的結果,但我無法弄清楚如何訪問「目的地」。
我最終想要做的是對XML文檔執行一個LINQ查詢,並將單個結果(下文中的示例中的Name和Author)綁定到單獨的文本框(txtName和txtAuthor),然後綁定子查詢的結果到一個列表框。我可以在單個查詢中執行此操作嗎?
[Return All Elements and Sub-elements]的可能重複(http://stackoverflow.com/questions/17218975/return-all-elements-and-sub-elements) –
你應該改善你的問題(並回應要求額外信息的評論),請勿重新發布。 –