如何在C#中将新节点添加为现有XML的根节点?
解决方案
你的问题在于当前代码是把<nodes>节点插入到原<node>根节点的内部,而实际需要将<node>放到新建的<nodes>节点中,让<nodes>成为根节点。
修改后的代码
public XmlDocument FunctionG() { XmlDocument xmlResponse = ExecuteGet(); XmlDocument xmlOperacion = new XmlDocument(); XmlNode aux; XmlNodeList nodeListCustom1 = xmlResponse.SelectNodes("/nodes/node/children/node[@ciType='Mabe_Operation']"); aux = nodeListCustom1[0]; // 优化:批量删除所有dimension节点(倒序遍历避免索引混乱) XmlNodeList dimensions = aux.SelectNodes("dimension"); for (int i = dimensions.Count - 1; i >= 0; i--) { aux.RemoveChild(dimensions[i]); } XmlNodeList children = aux.SelectNodes("children"); if (children.Count > 0) { aux.RemoveChild(children[0]); } xmlOperacion.LoadXml(aux.OuterXml); // 关键修改:将原<node>节点包裹到新的<nodes>根节点中 XmlNode newRoot = xmlOperacion.CreateElement("nodes"); XmlNode oldRoot = xmlOperacion.DocumentElement; xmlOperacion.RemoveChild(oldRoot); newRoot.AppendChild(oldRoot); xmlOperacion.AppendChild(newRoot); return xmlOperacion; }
关键修改说明
- 批量删除dimension节点:用循环替代三次重复代码,更简洁且避免硬编码删除次数,同时倒序遍历防止节点删除后索引偏移。
- 重构根节点结构:
- 创建
<nodes>节点作为新的根节点 - 移除原文档的
<node>根节点 - 将
<node>添加为<nodes>的子节点 - 把
<nodes>设置为文档的根节点
- 创建
修改后最终生成的XML结构即为你需要的:
<nodes> <node></node> </nodes>
内容的提问来源于stack exchange,提问作者Brian Martín Torres Fuentes
相关产品推荐
相关产品推荐

