使用xml.etree,如何创建命名空间属性" XML:lang"?

时间:2016-03-13 11:31:26

标签: python xml xml.etree

我正在尝试使用xml.etree为TMX格式创建一个简单的xml转换器。如何创建如下所示的语言属性:xml:lang

我尝试了什么:

    root = et.Element("tmx")
    body = et.SubElement(root, "body")
    tu = et.SubElement(body, "tu")
    tuv_en = et.SubElement(tu, "tuv", xml:lang="en")  # 'xml:lang' gets error
    tuv_zh = et.SubElement(tu, "tuv", xml:lang="zh")
    seg_en = et.SubElement(tuv_en, "segment").text="en text."
    seg_zh = et.SubElement(tuv_zh, "segment").text="zh text."
    tree = et.ElementTree(root)
    tree.write( file + ".xml")

我想要的是什么:

<tmx>
  <body>
    <tu>
      <tuv xml:lang="en">
        <seg>en text.</seg>
      </tuv>
      <tuv xml:lang="zh">
        <seg>zh text.</seg>
      </tuv>
    </tu>
  </body>
</tmx>

2 个答案:

答案 0 :(得分:3)

设置attrib关键字参数:

import xml.etree.ElementTree as et

root = et.Element("tmx")
body = et.SubElement(root, "body")

tu = et.SubElement(body, "tu")
et.SubElement(tu, "tuv", attrib={"xml:lang": "en"})
et.SubElement(tu, "tuv", attrib={"xml:lang": "zh"})

print(et.tostring(body))

这会产生:

<body><tu><tuv xml:lang="en" /><tuv xml:lang="zh" /></tu></body>

答案 1 :(得分:1)

如果你有一个现有的lxml etree dom并且不能使用ElementTree,你可以像这样设置属性:

from lxml import etree

element = etree.Element("element")

# This won't work: element.set("xml:lang", "en")
element.set("{http://www.w3.org/XML/1998/namespace}lang", "en")

print(etree.tostring(element))

结果:

<element xml:lang="en"/>