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

给XLIFF文件trans-unit元素加xml:space属性时出现ns0:前缀问题求助

XLIFF添加xml:space属性时出现ns0前缀的问题解决

问题背景

需求:给以下XLIFF文件的每个<trans-unit>元素添加xml:space="preserve"属性:

<?xml version="1.0" encoding="utf-8"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">

<file datatype="plaintext" source-language="en-US" target-language="de-DE" date="2023-01-19T14:30:55Z" xml:space="preserve">
<body>

<trans-unit size-unit="char" approved="no" maxwidth="70" id="TITLE">
    <source>Add test scripts to execution queue</source>
    <target state="translated">Testskripte zur Ausführungs-Queue hinzufügen</target>
</trans-unit>
<trans-unit size-unit="char" approved="no">
    <source>Dynamic ID</source>
    <target state="translated">Dynamic-ID</target>
</trans-unit>
<trans-unit size-unit="char" approved="no" maxwidth="132">
    <source>Identification</source>
    <target state="translated">Identifikation</target>
</trans-unit>

</body>
</file>
</xliff>

现有Python脚本执行后,会给XML所有元素自动加上ns0:前缀:

import xml.etree.ElementTree as ET

tree = ET.parse("input.xlf")
root = tree.getroot()

for trans_unit in root.iter("{urn:oasis:names:tc:xliff:document:1.2}trans-unit"):
    trans_unit.attrib["{http://www.w3.org/XML/1998/namespace}space"] = "preserve"

tree.write("output.xlf")

问题

该问题产生的原因是什么?如何改进脚本解决此问题?


问题原因

  • Python的xml.etree.ElementTree模块在处理带命名空间的XML时,若未提前注册命名空间与前缀的映射,会自动给所有命名空间下的元素生成默认前缀(比如ns0)。
  • 原脚本没有注册XLIFF的默认命名空间,导致输出时ElementTree自动为所有XLIFF元素添加了ns0:前缀。

改进方案

提前注册XLIFF的默认命名空间(绑定到空前缀,匹配原XML格式)和xml命名空间,这样输出时就能保持原XML的命名空间结构,不会生成额外前缀。

改进后的脚本:

import xml.etree.ElementTree as ET

# 注册命名空间:将XLIFF默认命名空间绑定到空前缀,xml命名空间绑定到xml前缀
ET.register_namespace("", "urn:oasis:names:tc:xliff:document:1.2")
ET.register_namespace("xml", "http://www.w3.org/XML/1998/namespace")

tree = ET.parse("input.xlf")
root = tree.getroot()

for trans_unit in root.iter("{urn:oasis:names:tc:xliff:document:1.2}trans-unit"):
    trans_unit.attrib["{http://www.w3.org/XML/1998/namespace}space"] = "preserve"

# 写入时指定编码和XML声明,与原文件格式保持一致
tree.write("output.xlf", encoding="utf-8", xml_declaration=True)

关键说明

  • ET.register_namespace("", "urn:oasis:names:tc:xliff:document:1.2"):让XLIFF默认命名空间使用空前缀,避免生成ns0:这类自动前缀。
  • ET.register_namespace("xml", "http://www.w3.org/XML/1998/namespace"):确保xml:space属性的xml前缀正确显示,不会被替换。
  • 写入时添加xml_declaration=True,保证输出文件包含XML声明,和原文件格式一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:30:39