Jiang Jiali
Jiang Jiali

Reputation: 37

add root elements in xml using XmlDocument C#

I want to add a root elements --testsuites into my existing xml report. My current report looks like this

<?xml version="1.0" encoding="utf-8"?>
 <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="Setup23" time="357" classname="classname">
  </testcase>
  </testsuite>

I want it change to

    <?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="Setup23" time="357" classname="classname">
      </testcase>
     </testsuite>
    </testsuites>

My current doesn't work on me

XmlDocument report = new XmlDocument();
report.Load(fileOfReport);
XmlElement root = report.CreateElement("root");
root.SetAttribute("testsuites","testsuites");
XmlElement child = report.CreateElement("child");
child.GetElementsByTagName("testsuite");
report.DocumentElement.AppendChild(root);
root.AppendChild(child);        
report.Save(fileOfReport);

Is there anyone can help?

Upvotes: 3

Views: 16000

Answers (1)

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

You need to call the CreateElement to create the node and append the required childs . Finally append the Newly created node to the Document .

 XmlDocument report = new XmlDocument();
    report.Load(fileOfReport);
    XmlElement root = report.CreateElement("testsuites");           
    var items = report.GetElementsByTagName("testsuite");
    for (int i = 0; i < items.Count; i++)
    {
        root.AppendChild(items[i]);
    }
    report.AppendChild(root);
    report.SaveAs(fileOfReport);

Upvotes: 2

Related Questions