繁体   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