简体   繁体   中英

LINQ to XML subquery to ListBox

I have an XML file that looks something like this:

<?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>

I have a LINQ to XML query that I have worked out with some help from this 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)
                          });

The trouble is, (1) I always get a nullreferenceerror and (2) I don't understand how to access the results of the second select. I can do something like:

        txtScriptTitle.Text = query.FirstOrDefault().Name;
        cmboAuthor.Text = query.FirstOrDefault().Author;

to show the results of the first two items, but I can't figure out how to access "Destination".

What I ultimately want to do is perform one LINQ query against the XML document and bind the single results (Name and Author in my example below) to individual text boxes (txtName and txtAuthor) and then bind the results of the subquery to a listbox. Can I do this in a single query?

Trying changing your query which populates Destination to

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

That will populate it with a List which you can then bind to your control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM