【问题标题】:Changing the value of a single node in XML更改 XML 中单个节点的值
【发布时间】:2017-12-04 20:13:25
【问题描述】:

我有以下 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!");

【问题讨论】:

  • 您的 XML sn-p 未显示 XML 的格式。您能否包含您正在使用的实际 XML,以便我们知道哪些值是元素以及哪些属性?
  • 我在问题中添加了用于创建 XML 文件的代码,希望对您有所帮助

标签: c# xml winforms


【解决方案1】:

您应该能够按如下方式更新年龄:

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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-27
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2019-12-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多