简体   繁体   English

遍历XML以获取所有子节点的文本值

[英]Iterate through XML to get all child nodes text value

i have a xml with following data. 我有以下数据的XML。 i need to get value of and all other attribute. 我需要获取值以及所有其他属性。 i return a python code there i get only first driver value. 我返回一个python代码,在那里我仅获得第一个驱动程序值。

My xml : 我的xml:

<volume name="sp" type="span" operation="create">
    <driver>HDD1</driver>
    <driver>HDD2</driver>
    <driver>HDD3</driver>
    <driver>HDD4</driver>
</volume>

My script: 我的剧本:

import xml.etree.ElementTree as ET
doc = ET.parse("vol.xml")
root = doc.getroot() #Returns the root element for this tree.
root.keys()          #Returns the elements attribute names as a list. The names are returned in an arbitrary order
root.attrib["name"]
root.attrib["type"]
root.attrib["operation"]

print root.get("name")
print root.get("type")
print root.get("operation")

for child in root:
    #print child.tag, child.attrib
    print root[0].text

My output: 我的输出:

    sr-query:~# python volume_check.py aaa
    sp
    span
    create
    HDD1
   sr-queryC:~#

I am not get HDD2 , HDD3 and HDD4 . 我没有得到HDD2HDD3HDD4 How to itirate through this xml to get all values? 如何通过此xml初始化以获取所有值? Any optimized way? 有没有优化的方法? I think any for loop can do that but not familiar with Python. 我认为任何for循环都可以做到这一点,但对Python并不熟悉。

In your for loop, it should be 在您的for循环中,应该是

child.text

not

root[0].text

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

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