更新文件XML [英] Update file XML
本文介绍了更新文件XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题:我有一个.xml文件.我想阅读并更新它.我写了代码:
I have a problem: I have a file .xml. I want read and update it. I written code:
private void Read_file()
{
XmlDocument document = new XmlDocument();
document.Load(@"D:\\Help_file.xml");
XmlNodeList myNoteList = document.GetElementsByTagName("product");
foreach (XmlElement node in myNoteList)
{
if (node.GetAttribute("id") == "1005")
{
richTextBox1.Text = node.SelectSingleNode("productName").InnerText;
//richTextBox2.Text = node.SelectSingleNode("productPrice").InnerText;
}
else if (node.GetAttribute("id") ==index)
{
richTextBox2.Text = node.SelectSingleNode("productName").InnerText;
}
}
}
和:
and :
private void Update_file()
{
FileStream fs = new FileStream(@"D:\\Help_file.xml", FileMode.Open);
XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);
XmlDocument document = new XmlDocument();
//document.Load(@"D:\\Help_file.xml");
XmlNodeList myNoteList = document.GetElementsByTagName("product");
foreach (XmlElement node in myNoteList)
{
if (node.GetAttribute("id") == "1005")
{
//richTextBox1.Text = node.SelectSingleNode("productName").InnerText;
w.WriteElementString("productName", richTextBox1.Text);
w.WriteEndElement();
}
}
}
Read_file()
运行成功,但Update_file()
不成功.
我不习惯使用xml.请帮助查看Update_file()
功能.谢谢!
With Read_file()
run successed but Update_file()
do not successed.
I''m not used to using xml. Please help review Update_file()
function. Thanks!
推荐答案
无论您使用XmlTextWriter做什么,即使您解决了问题,它也是错误的.您已经决定使用XmlDocument,请继续使用它!
从文件加载文件,将数据直接修改到文档节点上,并在准备好后写入此文档:
Whatever you do with XmlTextWriter, it''s wrong, even if you fix a problem. You already decided to use XmlDocument, keep using it!
Load it from file, modify data right onto document nodes, and write this document when ready:
public static void WriteXmlDocument(
XmlDocument doc,
outputFileName) {
using (XmlTextWriter writer =
new XmlTextWriter(outputFileName, Encoding.UTF8))) {
writer.Formatting = Formatting.Indented;
doc.WriteTo(writer);
} //using (important to dispose writer, otherwise it may not flush)
} //WriteXmlDocument
这篇关于更新文件XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文