Jiang Jiali
Jiang Jiali

Reputation: 37

Add child element in xml using XmlDocument C#

I want to add a child elements below root elements but to be the first child elements. My current xml is like this

<?xml version="1.0" encoding="utf-8"?>
<testsuites>
 <testsuite name="classname" tests="9" failures="3" errors="6" time="2919" disabled="0" skipped="0">
  <testcase name="Setup1" time="5" classname="classname">
  </testcase>
  <testcase name="Setup2" time="49" classname="classname">
  </testcase>
  <testcase name="Setup3" time="357" classname="classname">
  </testcase>
 </testsuite>
</testsuites>

After add the element , i want it look like this

<?xml version="1.0" encoding="utf-8"?>
<testsuites>
 <properties name ="namedata" value="valuedata">
 </properties>
  <testsuite name="classname" tests="9" failures="3" errors="6" time="2919" disabled="0" skipped="0">
   <testcase name="Setup1" time="5" classname="classname">
   </testcase>
   <testcase name="Setup2" time="49" classname="classname">
   </testcase>
   <testcase name="Setup3" time="357" classname="classname">
   </testcase>
  </testsuite>
</testsuites>

What i did is

XmlDocument report = new XmlDocument();
report.Load(fileOfReport);
XmlElement root = report.CreateElement("properties");
root.SetAttribute("property name", "namedata");
root.SetAttribute("value","valuedata");
var items = report.GetElementsByTagName("testsuite");
for(int i=0; i<items.Count; i++){
    child.AppendChild(items[i]);
}
report.AppendChild(root);
report.Save(fileOfReport);

The code shows properties as a root elements which include testsuite, but actually i want it as a child elemetns which is parallel with testsuite. How should i re-structure that? Note, i can only use xmlDocument not xDocument

Thanks

Upvotes: 0

Views: 5132

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14251

XmlDocument has plenty of useful methods. In this case, the PrependChild is convenient.

XmlDocument report = new XmlDocument();
report.Load(fileOfReport);

XmlElement root = report.CreateElement("properties");
root.SetAttribute("propertyname", "namedata");
root.SetAttribute("value", "valuedata");

report.DocumentElement.PrependChild(root);

report.Save(fileOfReport);

Upvotes: 1

Related Questions