我正在编写一个将数据存储到XML的程序。我不得不将数据从XML提取到DataGridView并编辑XML元素值。我尝试了很多代码,但它没有用。我究竟做错了什么? 哪一个更容易。 Linq命令或XMLWriter,XMLReader方式???? 下面是代码:
private void button2_Click(object sender, EventArgs e)
{
string sid = textBox1.Text;
string fname = textBox3.Text;
string lname = textBox2.Text;
string address = textBox4.Text;
string gender = radioButton1.Checked ? "эр" : "эм";
XmlDocument doc = new XmlDocument();
doc.Load("student.xml");
string tempid = doc.SelectSingleNode("root/Student/ID").InnerText;
if(tempid == sid)
{
doc.SelectSingleNode("root/Student/Fname").InnerText = fname;
doc.SelectSingleNode("root/Student/Lname").InnerText = lname;
doc.SelectSingleNode("root/Student/Address").InnerText = address;
doc.SelectSingleNode("root/Student/Gender").InnerText = gender;
}
和XML:
<?xml version="1.0" encoding="UTF-8"?>
-<root>
-<Student>
<ID>B140030123</ID>
<FName>Kent</FName>
<LName>Wayne</LName>
<Address>Gotham</Address>
<Gender>эр</Gender>
</Student>
</root>
如何循环请帮助:(
private void button2_Click(object sender, EventArgs e)
{
string sid = textBox1.Text;
string fname = textBox3.Text;
string lname = textBox2.Text;
string address = textBox4.Text;
string gender = radioButton1.Checked ? "эр" : "эм";
XmlDocument doc = new XmlDocument();
doc.Load("student.xml");
XmlNode node = doc.DocumentElement;
string tempid = doc.SelectSingleNode("root/Student/ID").InnerText;
foreach (var temp in doc.SelectSingleNode("root/Student/ID"))
{
if (tempid == sid)
{
doc.SelectSingleNode("root/Student/FName").InnerText = fname;
doc.SelectSingleNode("root/Student/LName").InnerText = lname;
doc.SelectSingleNode("root/Student/Address").InnerText = address;
doc.SelectSingleNode("root/Student/Gender").InnerText = gender;
}
}
doc.Save("student.xml");
}
答案 0 :(得分:0)
修改XmlDocument
对象不会更改xml文件。完成编辑后,您必须覆盖该文件。
XmlDocument doc = new XmlDocument();
doc.Load("student.xml");
string tempid = doc.SelectSingleNode("root/Student/ID").InnerText;
if(tempid == sid)
{
doc.SelectSingleNode("root/Student/Fname").InnerText = fname;
...etc
}
doc.Save("student.xml");
答案 1 :(得分:0)
拥有XML结构,您可以使用一种简单的方法:
var dataSet = new DataSet();
dataSet.ReadXml("student.xml");
dataGridView.DataSource = dataSet.Tables["Student"];
这就是全部!
您可以在DataGridView
中修改数据。您可以添加和删除行。
最后,将DataSet
保存到文件中:
dataSet.WriteXml("student.xml");