python元素树xml解析

时间:2012-11-16 07:42:23

标签: python xml-parsing

我使用Python元素树来解析xml文件

假设我有一个像这样的xml文件..

<html>
<head>
    <title>Example page</title>
</head>
<body>
    <p>hello this is first paragraph </p>
    <p> hello this is second paragraph</p>
</body>
</html>

有没有什么办法可以像p

一样完整地提取身体标签
desired= "<p>hello this is first paragraph </p> <p> hello this is second paragraph</p>"

3 个答案:

答案 0 :(得分:1)

以下代码可以解决问题。

import xml.etree.ElementTree as ET

root = ET.fromstring(doc)  # doc is a string containing the example file
body = root.find('body')
desired = ' '.join([ET.tostring(c).strip() for c in body.getchildren()])

现在:

>>> desired
'<p>hello this is first paragraph </p> <p> hello this is second paragraph</p>'

答案 1 :(得分:0)

您可以使用lxml库,lxml

所以,这段代码可以帮到你。

import lxml.html

htmltree = lxml.html.parse('''
<html>
<head>
<title>Example page</title>
</head>
 <body>
<p>hello this is first paragraph </p>
<p> hello this is second paragraph</p>
</body>
</html>''')
p_tags = htmltree.xpath('//p')
p_content = [p.text_content() for p in p_tags]

print p_content

答案 2 :(得分:0)

与@DavidAlber略有不同的方式,可以轻松选择孩子:

from xml.etree import ElementTree

tree = ElementTree.parse("example.xml")
body = tree.findall("/body/p")

result = []
for elem in body:
     result.append(ElementTree.tostring(elem).strip())

print " ".join(result)