向现有XML文件中的多个节点添加新元素
本文关键字:新元素 添加 节点 元素 XML 文件 | 更新日期: 2023-09-27 18:03:15
我有以下XML文件,目前有100多个客户端节点,我想使用c#向每个节点添加元素。
我的XML文件结构如下: <file_specs>
<client>
<account_number></account_number>
<client_name></client_name>
<file_type></file_type>
<file_extension></file_extension>
<file_hasdelimiter></file_hasdelimiter>
<file_delimiter></file_delimiter>
<central_one>false</central_one>
<central_code>none</central_code>
<central_two>false</central_two>
<c_two_code>none</c_two_code>
<header_line>true</header_line>
<has_quotes>true</has_quotes>
<start_line>1</start_line>
<has_one>true</has_one>
<one_column>2</one_column>
<has_two>true</has_two>
<two_column>12</two_column>
</client
我看了其他的答案,我尝试了各种解决方案。这个可以工作,但只适用于第一个客户端,其他所有客户端都不受影响:
XDocument doc = XDocument.Load(@"c:/xmlconfig/sample.xml");
doc.Root.Element("client").Add(new XElement("testing", "none"));
我尝试添加一个foreach循环,它为每个客户端节点添加了一个测试元素,但是它将所有这些元素添加到第一个条目中,其余的都不受影响。
XDocument doc = XDocument.Load(@"c:/xmlconfig/miss.xml");
foreach (var client in doc.Descendants("client"))
{
doc.Root.Element("client").Add(new XElement("testing", "none"));
}
我错过了什么?
您应该为每个客户端添加新元素:
XDocument doc = XDocument.Load(@"c:/xmlconfig/miss.xml");
foreach (var client in doc.Descendants("client"))
{
// use current client
client.Add(new XElement("testing", "none"));
}
让我们看看这里发生了什么:
foreach (var client in doc.Descendants("client"))
{
doc.Root.Element("client").Add(new XElement("testing", "none"));
}
对于每个客户端,执行的查询取root下的第一个客户端元素。然后向第一个客户端添加新元素。这个过程要重复很多次,就像xml中的客户机数量一样。最后测试添加到第一个客户端的元素N次。