将XML节点添加到多个父节点(具有相同的名称) [英] Add an XML node to multiple parent nodes(which have same name)

查看:65
本文介绍了将XML节点添加到多个父节点(具有相同的名称)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将XML节点添加到多个具有相同名称的父节点.但这只是添加到XML的Last节点,而不是全部.

I am trying to add an XML node to multiple parent nodes(which have same name). But it is only adding to the Last node of the XML and not in all.

输入XML

<Record>
 <Emp>
  <ID>12</ID>
  <Name>ABC</Name>
 </Emp>
 <Emp>
  <ID>12</ID>
  <Name>ABC</Name>
 </Emp>
</Record>

我想将Location元素添加到每个Emp节点.我的代码如下:

I want to add the Location element to every Emp node. My code is as below:

XmlNodeList xNodeList = doc.SelectNodes("/Record/Emp");
XmlElement xNewChild = doc.CreateElement("Location");
        xNewChild.InnerText = "USA";
        foreach (XmlNode item in xNodeList)
        {
            item.AppendChild(xNewChild);
        }
doc.Save(path);

但是我得到这样的输出:

but I am getting output like this:

 <Record>
 <Emp>
  <ID>12</ID>
  <Name>ABC</Name>
 </Emp>
 <Emp>
  <ID>12</ID>
  <Name>ABC</Name>
  <Location>USA</Location>
 </Emp>
</Record>

Location元素尚未添加到第一个Emp节点.

The Location element has not been added to the first Emp node.

注意:调试后,我发现即使第一个Emp节点也已添加了该元素.但是,在保存的XML文件中,我看到了这种奇怪的行为.

Note: After debugging, I am able to find that the element has been added even for the first Emp node. But, in the saved XML file I am seeing this strange behavior.

推荐答案

您的 xNewChild 是一个新元素.简单地将其添加到多个节点将仅序列化到最后一个节点.这样的更改应该起作用:

Your xNewChild is a single new element. Simply adding it to multiple nodes will only serialize to the last node. A change like this should work:

XmlNodeList xNodeList = doc.SelectNodes("/Record/Emp");
foreach (XmlNode item in xNodeList)
{
  XmlElement xNewChild = doc.CreateElement("Location");
  xNewChild.InnerText = "USA";
  item.AppendChild(xNewChild);
}
doc.Save(path);

这篇关于将XML节点添加到多个父节点(具有相同的名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆