c# - 向现有 Xml 文件添加新的父节点

我有以下 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);

我怎样才能做到这一点?


富国沪深
浏览 131回答 1
1回答

MM们

重命名你的根元素,当我运行你的代码时,它对我有用。请参阅下面我使用的 XML 和代码。XML:<?xml version="1.0" encoding="utf-8" standalone="yes"?><testsuites id="" name="Test Projekt test">&nbsp; <node_order />&nbsp; <details />&nbsp; <testsuite id="" name="Test Suite 1">&nbsp; &nbsp; <node_order />&nbsp; &nbsp; <details />&nbsp; &nbsp; <testsuite id="" name="Test Suite Operation 2">&nbsp; &nbsp; &nbsp; <node_order />&nbsp; &nbsp; &nbsp; <details />&nbsp; &nbsp; </testsuite>&nbsp; </testsuite>&nbsp; <testsuite id="" name="">&nbsp; &nbsp; <node_order />&nbsp; &nbsp; <details />&nbsp; </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");
打开App,查看更多内容
随时随地看视频慕课网APP