Как изменить существующий файл XML с помощью XmlDocument и XmlNode в C #
Я уже реализовал создание XML-файла ниже с XmlTextWriter при инициализации приложения.
И знаю, что я не знаю, как обновить значение idNode childNode с помощью XmlDocument & XmlNode .
Есть ли какое-то свойство для обновления значения 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");