You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将details.xml的properties节点插入company.xml的第二个company节点?

C# XML操作:将节点插入到第二个节点中

核心思路

用LINQ to XML(XDocument)简化XML操作,流程为:加载文档→提取目标节点→定位插入位置→执行插入→保存修改。

完整代码示例

using System;
using System.Linq;
using System.Xml.Linq;

class XmlNodeInsertion
{
    static void Main()
    {
        string tempDir = @"C:\Temp";
        string detailsPath = $@"{tempDir}\details.xml";
        string companyPath = $@"{tempDir}\company.xml";

        try
        {
            // 加载两个XML文档
            XDocument detailsDoc = XDocument.Load(detailsPath);
            XDocument companyDoc = XDocument.Load(companyPath);

            // 提取details.xml中<details>下的所有<properties>节点
            var propertiesNodes = detailsDoc.Root?
                .Element("details")?
                .Elements("properties");

            if (propertiesNodes == null || !propertiesNodes.Any())
            {
                Console.WriteLine("details.xml中未找到有效的<properties>节点");
                return;
            }

            // 定位第二个<company>节点(索引从0开始,第二个对应索引1)
            var targetCompanyNode = companyDoc.Root?
                .Elements("company")
                .ElementAtOrDefault(1);

            if (targetCompanyNode == null)
            {
                Console.WriteLine("company.xml中不存在第二个<company>节点");
                return;
            }

            // 将所有<properties>节点插入到目标<company>节点的子节点末尾
            targetCompanyNode.Add(propertiesNodes);

            // 保存修改后的company.xml
            companyDoc.Save(companyPath);
            Console.WriteLine("节点插入完成,文件已保存");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"操作出错:{ex.Message}");
        }
    }
}

关键细节说明

  • 节点定位:Elements("company").ElementAtOrDefault(1)通过索引直接获取第二个节点,ElementAtOrDefault避免索引越界抛出异常,返回null便于后续校验。
  • 空值保护:用?.空传播运算符防止节点不存在时触发空引用异常,同时增加节点存在性校验,避免无效操作。
  • 命名空间处理:如果XML带命名空间,需先定义命名空间对象,示例如下:
    XNamespace ns = "http://your-namespace-uri";
    var propertiesNodes = detailsDoc.Root?
        .Element(ns + "details")?
        .Elements(ns + "properties");
    var targetCompanyNode = companyDoc.Root?
        .Elements(ns + "company")
        .ElementAtOrDefault(1);
    
  • 插入位置调整:若要将插入到节点的指定位置(比如第一个子节点),可替换为AddFirst(propertiesNodes),或用InsertAfter/InsertBefore定位具体子节点后插入。

传统XmlDocument方案(可选)

如果习惯使用XmlDocument,可参考以下实现:

using System.Xml;

class XmlDocInsertion
{
    static void Main()
    {
        string detailsPath = @"C:\Temp\details.xml";
        string companyPath = @"C:\Temp\company.xml";

        XmlDocument detailsDoc = new XmlDocument();
        detailsDoc.Load(detailsPath);
        XmlDocument companyDoc = new XmlDocument();
        companyDoc.Load(companyPath);

        // 提取<properties>节点
        XmlNodeList propertiesNodes = detailsDoc.SelectNodes("//details/properties");
        if (propertiesNodes == null || propertiesNodes.Count == 0) return;

        // 定位第二个<company>节点
        XmlNodeList companyNodes = companyDoc.SelectNodes("//company");
        if (companyNodes == null || companyNodes.Count < 2) return;
        XmlNode targetCompany = companyNodes[1];

        // 导入节点并插入
        foreach (XmlNode propNode in propertiesNodes)
        {
            XmlNode importedNode = companyDoc.ImportNode(propNode, true);
            targetCompany.AppendChild(importedNode);
        }

        companyDoc.Save(companyPath);
    }
}

内容的提问来源于stack exchange,提问作者Kung Fu Ninja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 09:36:12