Skip to main content
 首页 » 编程设计

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

2024年02月13日9mq0036

我有以下 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 次。