2016-11-23 78 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