簡體   English   中英

LINQ to XML子查詢到ListBox

[英]LINQ to XML subquery to ListBox

我有一個看起來像這樣的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 to XML查詢,我已經在此SO Question的幫助下找到了。

    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),然后將子查詢的結果綁定到列表框。 我可以在一個查詢中執行此操作嗎?

嘗試更改將“ Destination填充到的查詢

Destination = c.Descendants("destination")
               .Select(e => e.Value)
               .Where(s => !string.IsNullOrEmpty(s))
               .ToList();

這將在其中填充一個列表,然后可以將其綁定到控件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM