使用xpath获取相应的XML节点

时间:2016-09-23 13:05:13

标签: python xml xpath lxml xliff

我有一个XML文件(实际上是一个xliff文件),其中一个节点有2个具有相同子结构的子节点(先验不知道,可能非常复杂并且每个<trans-unit>都有变化)。我正在使用python和lxml库...示例:

<trans-unit id="tu4" xml:space="preserve">
    <seg-source>
        <mrk mid="0" mtype="seg">
            <g id="1">...</g>
            <g id="2">...</g>
            <g id="3">...</g>
            <bx id="7"/>...
        </mrk>
        <mrk mid="1" mtype="seg">...</mrk>
        <mrk mid="2" mtype="seg">...
            <ex id="7"/>
            <g id="8"> FROM HERE </g>
        </mrk>
   </seg-source>
   <target xml:lang="en">
        <mrk mid="0" mtype="seg">
            <g id="1">...</g>
            <g id="2">...</g>
            <g id="3">...</g>
            <bx id="7"/>...
        </mrk>
        <mrk mid="1" mtype="seg">...</mrk>
        <mrk mid="2" mtype="seg">...
            <ex id="7"/>
            <g id="8"> TO HERE </g>
        </mrk>
   </target>
</trans-unit>

如您所见,2个节点<seg-source><target>具有完全相同的子结构。我的目标是导航到<seg-source>的每个节点,获取该节点的文本和尾部(我知道如何使用xpath执行此操作),翻译它们并最终(这就是我不喜欢的内容)。知道怎么做)分配到<target>翻译中的相应节点......

换句话说......假设我得到了节点&#34;从这里&#34; ...我怎样才能得到节点&#34;到这里&#34;?

1 个答案:

答案 0 :(得分:0)

如果您想要将它们配对,您只需将节点压缩在一起,这样就可以从每个节点中访问匹配的代码:

from lxml import etree

tree = etree.fromstring(x)
nodes = iter(tree.xpath("//*[self::seg-source or self::target]"))
for seq, tar in zip(nodes, nodes):
    # each node will be the matching nodes from each seq-source and target
    print(seq.xpath(".//*"))
    print(tar.xpath(".//*"))

由于每个trans-unit中只有两个,因此您可以使用nodes = iter(tree.xpath("//trans-unit/*")),因此内部节点的名称并不重要。

nodes = iter(tree.xpath("/trans-unit/*"))
for seq, tar in zip(nodes, nodes):
    print(seq.xpath(".//*"))
    print(tar.xpath(".//*"))

如果我们在您的示例上运行代码并打印每个id节点,您可以看到输出从每个节点获得一个:

In [2]: from lxml import etree

In [3]: tree = etree.fromstring(x)

In [4]: nodes = iter(tree.xpath("//trans-unit/*"))

In [5]: for seq, tar in zip(nodes, nodes):
   ...:         print(seq.xpath(".//g[@id='8']/text()"))
   ...:         print(tar.xpath(".//g[@id='8']/text()"))
   ...:     
[' FROM HERE ']
[' TO HERE ']

每个节点都是来自trans-unit的每个子节点的对应节点:

In [7]: for seq, tar in zip(nodes, nodes):
   ...:         print(seq.tag, tar.tag)
   ...:         for n1, n2 in zip(seq.xpath(".//*"),tar.xpath(".//*")):
   ...:                 print(n1.tag, n2.tag)
   ...:         
('seg-source', 'target')
('mrk', 'mrk')
('g', 'g')
('g', 'g')
('g', 'g')
('bx', 'bx')
('mrk', 'mrk')
('mrk', 'mrk')
('ex', 'ex')
('g', 'g')