XML 交叉引用

0 投票
1 回答
536 浏览
提问于 2025-04-16 16:38

我有一个XML文件,里面包含了一些ID,还有另一个XML文件也包含了相同的ID。 我想把这两个文件进行对比,从第二个文件中提取一些信息。 第一个文件里只包含我需要的那些ID。 比如,第一个文件里有ID 345、350、353、356,而第二个文件里有ID 345、346、347、348、349、350等等。 我想从第二个文件中提取出数据节点以及它的所有子节点。

第一个文件的结构:

<data>
    <node>
        <info>info</info>
        <id>345</id>
    </node>
    <node2>
        <node3>
                <info2>info</info2>
                <id>2</id>
        </node3>
        <otherinfo>1</otherinfo>
        <text type = "02">
                <role>info</role>
                <st>1</st>
        </text>
    </node2>
</data>

第二个文件的结构:

<data>
    <node>
        <info>info</info>
        <id>345</id>
    </node>
    <node2>And a bunch of other nodes</node2>
    <node2>And a bunch of other nodes</node2>
    <node2>And a bunch of other nodes</node2>
</data>

我试过用ruby/nokogiri来解决这个问题,但感觉进展不大。 我对任何脚本语言的解决方案都很感兴趣。

1 个回答

1

要从第一个xml字符串中提取所有的 id 值:

from lxml import etree

e1 = etree.fromstring(xml1)
ids = e1.xpath('//id/text()')

要从第二个xml字符串中提取所有的 <node> 元素,这些元素是第一个字符串中已知 id 值的父元素:

import re

e2 = etree.fromstring(xml2)
ns_re = dict(re="http://exslt.org/regular-expressions")
re_id = "|".join(map(re.escape, ids))
nodes = e2.xpath("//id[re:test(.,'^(?:%s)$')]/parent::node" % re_id,
                 namespaces=ns_re)

撰写回答