C# - Exporting listbox contents to XML
I have a l开发者_StackOverflow社区ist box control that contains key value pairs delimited by an "=" sign.
Example:
hot=cold
fast=slow
high=low
blue=red
I also have a button that will allow user to export this list in XML. How could I easily do that?
How do I crat the XML file what format should it be in?
You can use LINQ:
var xml = new XElement("Items",
from s in strings
let parts = s.Split('=')
select new XElement("Item",
new XAttribute("Key", parts[0]),
parts[1]
)
);
You can export the items to XML using LINQ, like this:
<asp:ListBox ID="listBox" runat="server">
<asp:ListItem Text="Joe" Value="1" />
<asp:ListItem Text="Jay" value="2" />
<asp:ListItem Text="Jim" Value="3" Selected="true" />
<asp:ListItem Text="Jen" Value="4" />
</asp:ListBox>
EDIT: Replaced old method with method that uses LINQ to XML.
public XDocument ParseListBoxToXml()
{
//build an xml document from the data in the listbox
XDocument lstDoc = new XDocument(
new XElement("listBox",
new XAttribute("selectedValue", listBox.SelectedValue ?? String.Empty), new XAttribute("selectedIndex", listBox.SelectedIndex), new XAttribute("itemCount", listBox.Items.Count),
new XElement("items",
from ListItem item in listBox.Items
select new XElement("item", new XAttribute("text", item.Text), new XAttribute("value", item.Value), new XAttribute("selected", item.Selected))
)
)
);
//return the xml document
return lstDoc;
}
And here is the XML output from the above method:
<listBox selectedValue="3" selectedIndex="2" itemCount="4">
<items>
<item Text="Joe" Value="1" Selected="false" />
<item Text="Jay" Value="2" Selected="false" />
<item Text="Jim" Value="3" Selected="true" />
<item Text="Jen" Value="4" Selected="false" />
</items>
</listBox>
Take a look at THIS tutorial on how to write XML files.
Or use XElement
as suggested by SLaks and use its Save() method to get the Xml-File/-Data. You can also write it directly to the response stream using that method.
Here is another alternative.
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
string fileName = @"C:\Temp\myXmlfile.xml";
using (XmlWriter writer = XmlWriter.Create(fileName, settings))
{
writer.WriteStartElement("items");
for (int i = 0; i < listBox1.Items.Count; i++)
{
writer.WriteStartElement("item");
string Key = listBox1.Items[i].ToString().Split('=')[0];
string Value = listBox1.Items[i].ToString().Split('=')[1];
writer.WriteElementString("key", Key);
writer.WriteElementString("value", Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
}
精彩评论