gpt4 book ai didi

c# - 向现有 XML 文件中的多个节点添加新元素

转载 作者:太空宇宙 更新时间:2023-11-03 21:32:05 24 4
gpt4 key购买 nike

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

对于每个客户端,您执行查询,该查询在根目录下获取第一个客户端元素。然后将新元素添加到第一个客户端。这重复了很多次,就像 xml 中的客户端数量一样。你最终测试元素添加到第一个客户端 N 次。

关于c# - 向现有 XML 文件中的多个节点添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23657935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com