如何使用Python的ElementTree获取孩子的孩子 [英] How to get the child of child using Python's ElementTree

查看:285
本文介绍了如何使用Python的ElementTree获取孩子的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个与PLC通信的Python文件。编译时,PLC将创建一个XML文件,该文件提供有关程序的重要信息。 XML看起来更像这样:

I'm building a Python file that communicates with a PLC. When compiling, the PLC creates a XML file that delivers important information about the program. The XML looks more less like this:

<visu>
    <time>12:34</time>
    <name>my_visu</name>
    <language>english</language>
    <vars>
        <var name="input1">2</var>
        <var name="input2">45.6</var>
        <var name="input3">"hello"</var>
    </vars>
</visu>

重要的部分位于子 vars下。我要使用Python创建一个文件,该文件在发送参数 input2时将显示 45.6。

The important part is found under child "vars". Using Python I want to make a file that when sending argument "input2" it will print "45.6".

到目前为止,我可以读取 visu的所有子级,但是不知道如何实际告诉Python在孩子的孩子中搜索。这是到目前为止我得到的:

So far I can read all children of "visu", but don't know how to actually tell Python to search among "the child of child". Here's is what I got so far:

tree = ET.parse("file.xml")
root = tree.getroot()
for child in root:
    if child.tag == "vars":
        .......
        if ( "childchild".attrib.get("name") == "input2" ):
            print "childchild".text

有什么想法可以完成脚本吗? (或者也许是更有效的编程方式?)

Any ideas how I can complete the script? (or maybe a more efficient way of programming it?)

推荐答案

您最好使用 XPath搜索此处:

name = 'input2'
value = root.find('.//vars/var[@name="{}"]'.format(name)).text

此搜索< var> 标记直接位于< vars> 标记下方,其属性 name 等于Python name 变量,然后检索该标记的文本值。

This searches for a <var> tag directly below a <vars> tag, whose attribute name is equal to the value given by the Python name variable, then retrieves the text value of that tag.

Demo:

>>> from xml.etree import ElementTree as ET
>>> sample = '''\
... <visu>
...     <time>12:34</time>
...     <name>my_visu</name>
...     <language>english</language>
...     <vars>
...         <var name="input1">2</var>
...         <var name="input2">45.6</var>
...         <var name="input3">"hello"</var>
...     </vars>
... </visu>
... '''
>>> root = ET.fromstring(sample)
>>> name = 'input2'
>>> root.find('.//vars/var[@name="{}"]'.format(name)).text
'45.6'

您可以用困难的方式执行此操作,并手动遍历所有元素;每个元素都可以直接循环:

You can do this the hard way and manually loop over all the elements; each element can be looped over directly:

name = 'input2'
for elem in root:
    if elem.tag == 'vars':
        for var in elem:
           if var.attrib.get('name') == name:
               print var.text

,但使用 element.find() element.find_all()可能会变得更加容易和简洁。

but using element.find() or element.find_all() is probably going to be easier and more concise.

这篇关于如何使用Python的ElementTree获取孩子的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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