【发布时间】:2016-11-23 17:33:54
【问题描述】:
我正在尝试制作一个小型 XML 编辑器。它加载一个 XML 文件,在列表框中显示所有书名(在我的示例文件中)。单击标题会在文本框中显示有关该书的所有信息。如果要修改信息,用户可以单击编辑按钮,现在可以在新文本框中编辑信息。最后,保存更改并清除两个文本框 - 如果可能,应将新更新的 XML 文件中的标题重新加载到列表框 (screenshot)。
感谢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;
}
}
【问题讨论】: