2011-09-01 36 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(); 
}