如何在 Python 中提取 XML 属性的值? [英] How do I extract value of XML attribute in Python?

查看:63
本文介绍了如何在 Python 中提取 XML 属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Python 提取 XML 文档中的属性值.

I need to extract the value of an attribute in an XML document using Python.

例如,如果我有一个这样的 XML 文档:

For example, If I have an XML document like this:

<xml>
    <child type = "smallHuman"/>
    <adult type = "largeHuman"/>
</xml>

如何将文本smallHuman"或largeHuman"存储在变量中?

How would I be able get the text 'smallHuman' or 'largeHuman' to store in a variable?

我对 Python 非常陌生,可能需要很多帮助.

I'm very new to Python and may require a lot of assistance.

这是我迄今为止尝试过的:

This is what I've tried so far:

#! /usr/bin/python

import xml.etree.ElementTree as ET


def walkTree(node):
    print node.tag
    print node.keys()
    print node.attributes[]
    for cn in list(node):
        walkTree(cn)

treeOne = ET.parse('tm1.xml')
treeTwo = ET.parse('tm3.xml')

walkTree(treeOne.getroot())

由于此脚本的使用方式,我无法将 XML 硬编码到 .py 文件中.

Due to the way this script will be used, I cannot hard-code the XML into the .py file.

推荐答案

使用 ElementTree 你可以使用 find 方法 &属性 .

Using ElementTree you can use find method & attrib .

示例:

import xml.etree.ElementTree as ET

z = """<xml>
    <child type = "smallHuman"/>
    <adult type = "largeHuman"/>
</xml>"""


treeOne = ET.fromstring(z)
print treeOne.find('./child').attrib['type']
print treeOne.find('./adult').attrib['type']

输出:

smallHuman
largeHuman

这篇关于如何在 Python 中提取 XML 属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆