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

如何使用C# Xml.Linq实现两个XML文件的翻译内容批量替换

XML翻译内容自动替换C#实现方案

完整实现代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace XmlTranslationReplace
{
    class Program
    {
        static void Main(string[] args)
        {
            // 自行修改为实际文件路径
            string sourceXmlPath = @"源译文XML文件路径";
            string targetXmlPath = @"待替换目标XML文件路径";
            string outputXmlPath = @"替换完成后的输出文件路径";

            try
            {
                // 1. 读取源文件生成UUID-译文映射字典
                Dictionary<string, string> translationMap = LoadTranslationMap(sourceXmlPath);

                // 2. 替换目标文件内容并输出
                ReplaceTargetXmlContent(targetXmlPath, outputXmlPath, translationMap);

                Console.WriteLine("替换完成,输出文件路径:" + outputXmlPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine("处理出错:" + ex.Message);
            }
        }

        private static Dictionary<string, string> LoadTranslationMap(string sourcePath)
        {
            XDocument sourceDoc = XDocument.Load(sourcePath);
            return sourceDoc.Descendants("node")
                .Where(node => node.Attribute("id")?.Value == "TranslatedStringKey")
                .Select(node => new
                {
                    Uuid = node.Elements("attribute")
                        .FirstOrDefault(attr => attr.Attribute("id")?.Value == "UUID")?
                        .Attribute("value")?.Value,
                    Content = node.Elements("attribute")
                        .FirstOrDefault(attr => attr.Attribute("id")?.Value == "Content")?
                        .Attribute("value")?.Value
                })
                .Where(kv => !string.IsNullOrEmpty(kv.Uuid) && !string.IsNullOrEmpty(kv.Content))
                .ToDictionary(kv => kv.Uuid, kv => kv.Content);
        }

        private static void ReplaceTargetXmlContent(string targetPath, string outputPath, Dictionary<string, string> translationMap)
        {
            XDocument targetDoc = XDocument.Load(targetPath);
            foreach (XElement contentNode in targetDoc.Descendants("content"))
            {
                string key = contentNode.Attribute("Key")?.Value;
                if (key != null && translationMap.TryGetValue(key, out string newContent))
                {
                    contentNode.Value = newContent;
                }
            }
            targetDoc.Save(outputPath);
        }
    }
}

核心逻辑说明

  • 先解析源译文XML,提取所有TranslatedStringKey类型节点,建立UUID到对应译文的映射字典,匹配效率更高
  • 解析待替换的目标XML,遍历所有content节点,通过Key属性匹配映射字典中的译文,匹配成功则替换节点文本内容
  • 最终将修改后的文件另存为新文件,避免直接覆盖原始文件导致数据丢失

特殊场景适配

  • 如果源XML是无统一根节点的片段,加载时需要开启片段支持避免格式校验报错:
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(sourcePath, settings))
{
    XDocument sourceDoc = XDocument.Load(reader);
    // 后续查询逻辑和上文一致
}
  • 如果实际XML包含默认命名空间,需要先声明命名空间再查询:
XNamespace ns = "你的实际命名空间URI";
// 所有节点名改为 ns + "node" 格式即可正常查询
  • 可根据实际业务场景调整空值判断逻辑,适配部分节点缺失属性的特殊情况

内容的提问来源于stack exchange,提问作者Jordi Mata Garcia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:21:00