我有以下XML文档:
<People>
<Person>
<Name>Dylan</Name>
<Email>email</Email>
<Age>4</Age>
</Person>
<Person>
<Name>Name</Name>
<Email>name</Email>
<Age>16</Age>
</Person>
<Person>
<Name>ok</Name>
<Email>name</Email>
<Age>16</Age>
</Person>
</People>
这是用于创建文件的代码,希望有所帮助。 我试图通过他们的名字选择某个人,并将他们的年龄更新为另一个值。我设法将用户输入的名称与文档中的名称进行比较,但在此之后不知道如何更新年龄。
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Dylan\\Desktop\\people.xml");
string name = textBox1.Text;
bool correct = false;
foreach (XmlNode node in doc.SelectNodes("//Person"))
{
string Name = node.SelectSingleNode("Name").InnerText;
if (Name == name)
{
//code to change age
}
if (correct == true) break;
}
这是用于创建文件的代码:
XmlTextWriter x = new XmlTextWriter("C:\\Users\\Dylan\\Desktop\\people.xml", Encoding.UTF8);
x.Formatting = Formatting.Indented;
x.WriteStartElement("People");
x.WriteStartElement("Person");
x.WriteStartElement("Name");
x.WriteString(textBox1.Text);
x.WriteEndElement();
x.WriteStartElement("Email");
x.WriteString(textBox2.Text);
x.WriteEndElement();
x.WriteStartElement("Age");
x.WriteString(numericUpDown1.Value.ToString());
x.WriteEndElement();
x.WriteEndElement();
x.WriteEndElement();
x.Close();
MessageBox.Show("Created!");
答案 0 :(得分:0)
您应该能够按如下方式更新年龄:
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Dylan\\Desktop\\people.xml");
string name = textBox1.Text;
bool correct = false;
foreach (XmlNode node in doc.SelectNodes("//Person"))
{
string Name = node.SelectSingleNode("Name").InnerText;
if (Name == name)
{
// Using the Person node, select the Age node
XmlNode ageNode = node.SelectSingleNode("Age");
// Update the value with whatever new value is required
ageNode.InnerText = "10";
}
if (correct == true) break;
}
// Remember to save the changes!
doc.Save("C:\\Users\\Dylan\\Desktop\\people.xml");