如何使用C#中的XmlDocument和XmlNode修改现有的XML文件

我已经实现了在应用程序初始化时使用XmlTextWriter创建下面的XML文件。

并且知道我不知道如何使用XmlDocumentXmlNode更新childNode id值。

是否有一些属性来更新id值? 我试过InnerText但失败了。 谢谢。

                              

你需要做这样的事情:

 // instantiate XmlDocument and load XML from file XmlDocument doc = new XmlDocument(); doc.Load(@"D:\test.xml"); // get a list of nodes - in this case, I'm selecting all  nodes under // the  node - change to suit your needs XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID"); // loop through all AID nodes foreach (XmlNode aNode in aNodes) { // grab the "id" attribute XmlAttribute idAttribute = aNode.Attributes["id"]; // check if that attribute even exists... if (idAttribute != null) { // if yes - read its current value string currentValue = idAttribute.Value; // here, you can now decide what to do - for demo purposes, // I just set the ID value to a fixed value if it was empty before if (string.IsNullOrEmpty(currentValue)) { idAttribute.Value = "515"; } } } // save the XmlDocument back to disk doc.Save(@"D:\test2.xml");