在python中打印子节点及其xml标签

时间:2015-08-14 17:47:26

标签: python xml elementtree

我有一个名为m.xml的文件,其中包含以下内容:

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

我想得到如下结果:

<driver>HDD1</driver>
<driver>HDD2</driver>
<driver>HDD3</driver>
<driver>HDD4</driver>

我正在尝试使用以下代码

import xml.etree.ElementTree as ET
root = ET.parse('m.xml')
for nod in root.findall("./driver"):
    print nod.text

我得到以下结果:

HDD1
HDD2
HDD3
HDD4

如何获取标签而不仅仅是文本值?

2 个答案:

答案 0 :(得分:0)

要将元素显示为XML文本,请使用ElementTree.tostring() function

Enter a string: 1234
Result: 1234╠╠╠╠╠╠╠╠╠╠╠1234

演示:

import xml.etree.ElementTree as ET
root = ET.parse('m.xml')
for nod in root.findall("./driver"):
    print ET.tostring(nod)

答案 1 :(得分:0)

使用BeautifulSoup解析XML。这很简单:

from bs4 import BeautifulSoup as Soup

with open("sample.xml", "r") as f:
    target_xml = f.read()

# create a `Soup` object
soup = Soup(target_xml, "xml")                                                                                                        

# loop through all <driver> returned as a list and prints all 
for d in soup.find_all("driver"):
    print(d)