2011-09-01 37 views
0

我有一个列表框控件,其中包含由“=”符号分隔的键值对。C# - 导出列表框内容到XML

例子:

热=冷

快=慢

高=低

蓝色=红色

我也有一个按钮,允许用户导出该列表中的XML。我怎么能轻松做到这一点?

如何克隆XML文件应该使用哪种格式?

+0

你可以做一个plist,苹果风格......我不明白你的意思是“格式”。总而言之, myKey可以工作... – Kheldar

回答

2

你可以使用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] 
    ) 
); 
+0

不错的代码... :) –

+0

这太棒了!在相关说明中,我怎么能在列表框中对列表进行排序?我希望能够按键和价值进行排序。 – PercivalMcGullicuddy

+0

添加“OrderBy”条目 – SLaks

0

THIS教程如何编写XML文件看看。
或按照SLak建议的XElement使用它的Save()方法来获取Xml-File/-Data。您也可以使用该方法将其直接写入响应流。

1

可以使用LINQ,像这样的项目导出到XML:

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

编辑:替换旧方法与使用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; 
} 

这里是从上述方法输出的XML:

<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> 
+0

这非常有帮助,谢谢! – mack

+0

不客气。很高兴帮助! –

0

下面是另一种选择。

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(); 
}