简体   繁体   English

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

[英]printing child nodes along with their xml tags in python

I have a file called m.xml which has the following content: 我有一个名为m.xml的文件,其内容如下:

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

I would like to get result as follows: 我想得到如下结果:

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

I am trying to use the following code 我正在尝试使用以下代码

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

I am getting the following result: 我得到以下结果:

HDD1
HDD2
HDD3
HDD4

How do I get the tags also and not just the textual values? 如何获得标签,而不仅仅是文本值?

To show the element as XML text, use the ElementTree.tostring() function : 要将元素显示为XML文本,请使用ElementTree.tostring()函数

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

Demo: 演示:

>>> import xml.etree.ElementTree as ET
>>> root = ET.fromstring('''\
... <volume name="sp" type="span" operation="create">
...     <driver>HDD1</driver>
...     <driver>HDD2</driver>
...     <driver>HDD3</driver>
...     <driver>HDD4</driver>
... </volume>
... ''')
>>> for nod in root.findall("./driver"):
...     print ET.tostring(nod)
... 
<driver>HDD1</driver>

<driver>HDD2</driver>

<driver>HDD3</driver>

<driver>HDD4</driver>

Use BeautifulSoup to parse XML. 使用BeautifulSoup解析XML。 It's very simple: 很简单:

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)

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

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