How to modify existing XML file with XmlDocument and XmlNode in C#

前端 未结 1 1327
梦如初夏
梦如初夏 2020-12-01 05:31

I already implemented to create the XML file below with XmlTextWriter when application initialization.

And know I don\'t know how to update the chi

相关标签:
1条回答
  • 2020-12-01 05:41

    You need to do something like this:

    // 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 <AID> nodes under
    // the <GroupAIDs> 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");
    
    0 讨论(0)
提交回复
热议问题