2016-11-23 82 views
0

我試圖製作一個小的XML編輯器。它加載一個XML文件,在列表框中顯示所有書名(在我的示例文件中)。點擊標題可以在文本框中顯示關於該書的所有信息。如果信息應該修改,用戶可以點擊編輯按鈕,現在可以在新的文本框中編輯信息。最後,保存更改並清除兩個文本框 - 並且,如果可能的話,應該將新更新的XML文件的標題重新加載到列表框(screenshot)中。使用Linq編輯元素並保存到XML文件

由於this post,列表框和第一個文本框操作正常。 當我嘗試將XML值發送到第二個文本框時出現問題。任何更改都不會被保存,或者如果它們是,XML文件的其餘部分消失。

我想一個解決方案可能包括將信息(及其更改)添加到新的XML元素,然後刪除舊的元素,但到目前爲止,我一直在嘗試一段時間,現在我可以不知道該怎麼做。這是出於同樣的原因,我知道這是不好的風格,我的代碼停在問題開始的地方。如果有人能幫助我,我會很高興。

我的示例XML:

<?xml version='1.0'?> 
<!-- This file represents a fragment of a book store inventory database --> 
<books> 
    <book genre="autobiography"> 
    <title>The Autobiography of Benjamin Franklin</title> 
    <author>Franklin, Benjamin</author> 
    <year>1981</year> 
    <price>8.99</price> 
    </book> 
    <book genre="novel"> 
    <title>The Confidence Man</title> 
    <author>Melville, Herman</author> 
    <year>1967</year> 
    <price>11.99</price> 
    </book> 
    <book genre="philosophy"> 
    <title>The Gorgias</title> 
    <author>Plato</author> 
    <year>1991</year> 
    <price>9.99</price> 
    </book> 
</books> 

而且我的.cs

private void btnLoadXML_Click(object sender, EventArgs e) 
    { 
     var xmlDoc = XDocument.Load("books03.xml"); 

     var elements = from ele in xmlDoc.Elements("books").Elements("book") 
         where ele != null 
         select ele; 

     bookList = elements.ToList(); 

     foreach (var book in bookList) 
     { 
      string title = book.Element("title").Value; 
      listBox1.Items.Add(title); 
     } 
    } 

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     var book = bookList[listBox1.SelectedIndex]; 

     textBox1.Text = 
      "Title: " + book.Element("title").Value + Environment.NewLine + 
      "Author: " + book.Element("author").Value + Environment.NewLine + 
      "Year: " + book.Element("year").Value + Environment.NewLine + 
      "Price: " + book.Element("price").Value; 
    } 

    private void btnEdit_Click(object sender, EventArgs e) 
    { 
     textBox2.Visible = true; 
     btnSaveClose.Visible = true; 
    } 
} 

回答

0

嘗試XML LINQ:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILENAME); 
      string searchName = "The Autobiography of Benjamin Franklin"; 
      XElement book = doc.Descendants("book").Where(x => (string)x.Element("title") == searchName).FirstOrDefault(); 

      XElement price = book.Element("price"); 

      price.SetValue("10.00"); 
     } 
    } 
} 
+0

但我怎麼在我的代碼實現它?以某種方式在'btn_edit()'下添加它? – Cunctator03