简体   繁体   English

带有 ElementTree 的 Python XML 解析

[英]Python XML PArse with ElementTree

I have an XML file with the following format:我有一个具有以下格式的 XML 文件:

<metadata>
    <groupId>stuff</groupId>
    <artifactId>stuff</artifactId>
    <versioning>
        <latest>stuff</latest>
        <release>stuff</release>
        <versions>
            <version>1</version>
            <version>2</version>
            <version>3</version>
        </versions>
        <lastUpdate>stuff</lastUpdate>
    </versioning>
</metadata>

And I have tried the following code:我已经尝试了以下代码:

root = ET.fromstring(data_as_string)

    for version in root.iter('versions'):
       print version.attrib

But it is printing 'versioning' only N times...但它只打印了 N 次“版本控制”......

I'd like to be able to extract the latest version value from the highest numbered version tag which is 3. Any help please?我希望能够从编号为 3 的最高版本标签中提取最新版本值。请问有什么帮助吗?

Use this Python script:使用这个 Python 脚本:

from xml.etree import ElementTree as ET 
xml = ET.parse('input.xml')
last = xml.findall("versioning/versions/version[last()]")
if len(last) > 0:
  print last[0].text

Its output is它的输出是

3 3

which is the last version element.这是最后一个version元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM