python - 使用python在XML中不同元素具有相同名称时复制属性信息

标签 python xml elementtree

所以,这是我的 XML 树:

<?xml version="1.0"?>
<api>
    <query>
        <normalized>
            <n from="Brain_cancer" to="Brain cancer" />
        </normalized>
        <redirects>
            <r from="Brain cancer" to="Brain tumor" 
            />
        </redirects>
        <pages>
            <page pageid="37284" ns="0" title="Brain tumor">
                <revisions>
                    <rev revid="412658600" parentid="412501243" user="Andycjp" userid="55014" timestamp="2011-02-08T03:35:27Z" size="59870" sha1="fe1ff25c27ebc86572aa4be8201cb813e1bf3d32" comment="/* Psychological and behavioral consequences */"  contentformat="text/x-wiki" contentmodel="wikitext" xml:space="preserve">
                    </rev>
                </revisions>
            </page>
        </pages>
    </query>
    <warnings>
        <revisions xml:space="preserve">
        </revisions>
        <result xml:space="preserve">
        </result>
    </warnings>
    <query-continue>
        <revisions rvcontinue="456175380" 
        />
    </query-continue>
</api>

因此,您可以看到,“修订”元素出现在不同级别的两个不同位置。我的目标是到达属性“rvcontinue”(其路径是 api/query-continue/revisions)以将其值复制到新变量中。这可能是因为我没有得到正确的结果,但 elementTree 和 xpath 到目前为止还不起作用。

这就是我到目前为止所做的,但没有进展

import xml.etree.ElementTree as ET
tree = ET.parse('Brain_tumor_5.xml')

for elem in tree.getiterator():
    if elem.tag=='{http://www.namespace.co.uk}query-continue':
        output = {}
        for elem1 in list(elem):
            if elem1.tag=='{http://www.namespace.co.uk}revisions':
                output['rvcontinue']=elem1.text
        print output

p = tree.find("./api/query-continue/revisions[@rvcontinue=]")
q = p.attrib
print q

最佳答案

我也主要使用lxml,所以我不知道etree是怎么回事,但它似乎 从树中查找不起作用,但从根查找确实有效:

>>> tree.getroot().find( 'query-continue/revisions[@rvcontinue]' ).attrib['rvcontinue']
'456175380'

另外:我不知道上面是否只是一个拼写错误,但是:

p = tree.find("./api/query-continue/revisions[@rvcontinue=]")

将给出 SyntaxError: invalid predicate

添加注释:tree.find( 'api' ) 似乎返回 None,

tree.find( '.' ) 返回 <Element 'api' at 0x1004e5f10 >

所以 tree.find( './query-continue/revisions[@rvcontinue]' )

也可以。

关于python - 使用python在XML中不同元素具有相同名称时复制属性信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14613637/

相关文章:

android - 创建圆形

python - 在Python中循环遍历文件目录

Python sklearn预测函数

python - Pygame错误: not able to open . wav文件

java - 0xaa 和 0x55 在做什么?

python - 递归调用函数

java - 从 XSD 获取完整的 XML 结构

python - XPath:选择具有空值的标记

python - 使用路径和值编写 xml

python - 使用 Python 解析 Alexa XML