Pergunta

I'm having issues correctly serializing selected data from a c# winforms listbox into an XML file.

// save xml config
SessionConfig config = new SessionConfig();

foreach(String listitem in mylistbox.SelectedItems)
{
    config.myItems = listitem;
}

config.Serialize(config);

and here's the SessionConfig class

public class SessionConfig
{
  // mylistbox
  public string myItems { get; set; }

  public void Serialize(SessionConfig details)
  {
      XmlSerializer serializer = new XmlSerializer(typeof(SessionConfig));
      using (TextWriter writer = new StreamWriter(string.Format("{0}\\config.xml", Application.StartupPath)))
      {
          serializer.Serialize(writer, details);
      }
  }
}

This will output an XML file like this:

<?xml version="1.0" encoding="utf-8"?>
<SessionConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <myItems>Item</myItems>
</SessionConfig>

What I'm trying to do is serialize all selected items, not just one item. And I would like to put each item in its own <Item> tag under the parent <myItems> node...like this:

<?xml version="1.0" encoding="utf-8"?>
<SessionConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <myItems>
    <Item>Item</Item>
  </myItems>
</SessionConfig>

I then want to be able to use the XML file to grammatically set the listbox selected items, but I'm not sure how I should go by looping through the node values.

This is what I have so far to read the values from my config file:

XmlDocument xml = new XmlDocument();
xml.Load(string.Format("{0}\\config.xml", Application.StartupPath));
XmlNode anode = xml.SelectSingleNode("/SessionConfig");
if (anode != null)
{
  if (anode["MyItems"] != null) 
}
Foi útil?

Solução

The myItems property in the SessionConfig class needs to be a list. It's currently just a string and you'll only ever get the last value from the listbox since you overwrite the previous value each time at the line config.myItems = listitem;

Using a structure like this should get you the structure you're looking for:

    public Item MyItems { get; set; }

    [CollectionDataContract(ItemName = "Item")]
    public class Item : List<string>{}

Then instead of using config.myItems = listitem; to add each item - you would use config.MyItems.Add(listItem)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top