我有以下xml文件,想在现有的最后一个节点之后添加一个新的父节点。
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<testsuite id="" name="Test Projekt test">
<node_order />
<details />
<testsuite id="" name="Test Suite 1">
<node_order />
<details />
<testsuite id="" name="Test Suite Operation 2">
<node_order />
<details />
</testsuite>
</testsuite>
</testsuite>
<new node here>
我尝试使用以下代码,但是没有用
XmlElement testsuite = doc_save.CreateElement("testsuite");
XmlAttribute ID = doc_save.CreateAttribute("id");
XmlAttribute Name = doc_save.CreateAttribute("name");
XmlElement node_order = doc_save.CreateElement("node_order");
XmlElement details = doc_save.CreateElement("details");
doc_save.DocumentElement.AppendChild(testsuite);
testsuite.Attributes.Append(ID);
testsuite.Attributes.Append(Name);
testsuite.AppendChild(node_order);
testsuite.AppendChild(details);
我该怎么做?
答案 0 :(得分:0)
通过@hotfix扩展注释,重命名您的根元素,当我运行您的代码时,它对我有用。请在下面查看我使用的XML和代码。
XML:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<testsuites id="" name="Test Projekt test">
<node_order />
<details />
<testsuite id="" name="Test Suite 1">
<node_order />
<details />
<testsuite id="" name="Test Suite Operation 2">
<node_order />
<details />
</testsuite>
</testsuite>
<testsuite id="" name="">
<node_order />
<details />
</testsuite>
</testsuites>
代码:
XmlDocument document = new XmlDocument();
document.Load(@"your\xml\file");
XmlElement testsuite = document.CreateElement("testsuite");
XmlAttribute ID = document.CreateAttribute("id");
XmlAttribute Name = document.CreateAttribute("name");
XmlElement node_order = document.CreateElement("node_order");
XmlElement details = document.CreateElement("details");
document.DocumentElement.AppendChild(testsuite);
testsuite.Attributes.Append(ID);
testsuite.Attributes.Append(Name);
testsuite.AppendChild(node_order);
testsuite.AppendChild(details);
document.Save(@"your\xml\file");