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

求可实现无重复合并两个XML翻译文件的PowerShell脚本

PowerShell 合并翻译XML去重脚本

以下是可直接使用的脚本,可实现两个翻译XML文件按trans-unit节点的id属性去重合并,输出为3.xml:

# 配置文件路径,可替换为你的实际文件路径
$xml1Path = "XML1.xml"
$xml2Path = "XML2.xml"
$outputPath = "3.xml"

# 用哈希表做去重容器,键为trans-unit的id属性
$transUnitMap = @{}

# 读取第一个XML文件的翻译单元,优先保留XML1的重复项
$xml1 = New-Object System.Xml.XmlDocument
$xml1.Load($xml1Path)
foreach ($unit in $xml1.SelectNodes("//trans-unit")) {
    if (-not $transUnitMap.ContainsKey($unit.id)) {
        $transUnitMap[$unit.id] = $unit.CloneNode($true)
    }
}

# 读取第二个XML文件的翻译单元,跳过已存在的id
$xml2 = New-Object System.Xml.XmlDocument
$xml2.Load($xml2Path)
foreach ($unit in $xml2.SelectNodes("//trans-unit")) {
    if (-not $transUnitMap.ContainsKey($unit.id)) {
        $transUnitMap[$unit.id] = $unit.CloneNode($true)
    }
}

# 构建输出XML结构
$outputXml = New-Object System.Xml.XmlDocument
$outputXml.AppendChild($outputXml.CreateXmlDeclaration("1.0", "utf-8", $null)) | Out-Null
$groupNode = $outputXml.CreateElement("group")
$groupNode.SetAttribute("id", "body")
$outputXml.AppendChild($groupNode) | Out-Null

# 导入去重后的所有翻译单元
foreach ($unit in $transUnitMap.Values) {
    $importedNode = $outputXml.ImportNode($unit, $true)
    $groupNode.AppendChild($importedNode) | Out-Null
}

# 保存为无BOM的UTF-8编码文件,和原文件编码格式一致
$xmlSaveSettings = New-Object System.Xml.XmlWriterSettings
$xmlSaveSettings.Encoding = New-Object System.Text.UTF8Encoding($false)
$xmlSaveSettings.Indent = $true
$xmlWriter = [System.Xml.XmlWriter]::Create($outputPath, $xmlSaveSettings)
$outputXml.WriteTo($xmlWriter)
$xmlWriter.Flush()
$xmlWriter.Close()

注意事项

  • 如果重复id需要优先保留XML2的内容,调换两个XML文件的读取顺序即可
  • 输出文件完全保留原节点的所有属性、内容和格式规范

内容的提问来源于stack exchange,提问作者user17079618

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:57:00