views:

27

answers:

1

So I have decided to use XDocument to create a XML file, which was working great until I came across a part where I have to find all the selected items in a ListBox. I am unsure how I should format this.

     XDocument xmlDoc = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("Created: " + DateTime.Now.ToString()),
                    new XElement("Trip",
                        new XElement("TripDetails",
                            new XElement("Departure", txtDeparture.Text),
                            new XElement("Return", txtReturn.Text),                     
                             new XElement("Purpose", txtPurpose.Text),
                             new XElement("Region", ddlRegion.SelectedValue.ToString()),
  //Not working                            
                             new XElement("Countries", 
                             foreach(string x in lstCountry.SelectedValue)
                             {
                                 new XElement("Country",x);
                             }
                            )
                          )
                        )  
                       );

I want to output each selected country in child nodes under Countries

+1  A: 

LINQ to XML is really nice in this respect - if you provide it with an iterable piece of content, it will iterate. Try this:

XDocument xmlDoc = new XDocument(
       new XDeclaration("1.0", "utf-8", "yes"),
       new XComment("Created: " + DateTime.Now.ToString()),
       new XElement("Trip",
           new XElement("TripDetails",
               new XElement("Departure", txtDeparture.Text),
               new XElement("Return", txtReturn.Text),                     
               new XElement("Purpose", txtPurpose.Text),
               new XElement("Region", ddlRegion.SelectedValue.ToString()),
               new XElement("Countries",
                    lstCountry.SelectedValues
                              .Cast<string>()
                              .Select(x => new XElement("Country", x))
              )
          )  
      );

Note that I've changed SelectedValue to SelectedValues to get multiple values. If that's not what you want, you should hopefully be able to adjust it accordingly.

Jon Skeet
@Jon Skeet thanks so much, but ListBox does not contain a definition for selectedValues. Not sure how to pull the multiple values
Spooks
got this to work by getting selectedIndices and no cast needednew XElement("Countries", lstCountry.GetSelectedIndices() .Select(x => new XElement("Country", x) )thanks again
Spooks