Search code examples
c#xmldocument

add xmlElement into a XmlNode


How to add an element into a XmlNode.

var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
XmlNode nodes = xmlDoc.SelectSingleNode("/configuration/schedulers");

XML Example:

<schedulers>
<Scheduler name="test1" alert="4" timerType="type1" cronExpression="0/10 * * * * ?">
  <property name="customerName" value="customerA" />
</Scheduler>
<Scheduler name="test2" alert="3" timerType="type2" cronExpression="0/15 * * * * ?" />
<Scheduler name="test3" maxFailureAlert="3" timerType="Type3" cronExpression="0/20 * * * * ?" />

And I want to add new scheduler

<schedulers>
  <Scheduler name="test1" alert="4" timerType="type1" cronExpression="0/10 * * * * ?">
    <property name="customerName" value="COMMON_MODEL" />
  </Scheduler>
  <Scheduler name="test2" alert="3" timerType="type2" cronExpression="0/15 * * * * ?" />
  <Scheduler name="test3" maxFailureAlert="3" timerType="Type3" cronExpression="0/20 * * * * ?" />
  <Scheduler name="test4" maxFailureAlert="3" timerType="Type3" cronExpression="0/50 * * * * ?" />
</schedulers>

Solution

  • You can use XmlDocument.CreateElement method to create an element:

    var xmlDoc = new XmlDocument();
    xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    XmlNode nodes = xmlDoc.SelectSingleNode("/configuration/schedulers");
    
    var newElement = xmlDoc.CreateElement("Scheduler");
    

    Then, you can set any attributes using SetAttribute:

    newElement.SetAttribute("name", "test4"); 
    newElement.SetAttribute("maxFailureAlert", "3"); 
    newElement.SetAttribute("timerType", "Type3"); 
    newElement.SetAttribute("cronExpression", "0/50 * * * * ?"); 
    

    And append a new element to your existing one:

    nodes.AppendChild(newElement);
    

    Don't forget to save a document:

    xmlDoc.Save(filePath);