使用xml标记内的html标记进行lxml xml解析 [英] lxml xml parsing with html tags inside xml tags
问题描述
<xml>
<maintag>
<content> lorem <br>ipsum</br> <strong> dolor sit </strong> and so on </content>
</maintag>
</xml>
我定期解析的xml文件可能在内容标签中包含html标签,如上所示.
The xml file that i regularly parse, may have html tags inside of content tag as shown above.
这是我解析文件的方式:
Here how i parse the file:
parser = etree.XMLParser(remove_blank_text=False)
tree = etree.parse(StringIO(xmlFile), parser)
for item in tree.iter('maintag'):
my_content = item.find('content').text
#print my_content
#output: lorem
因此,结果为my_content =' lorem ',而不是-我想看到的-'lorem< br> ipsum< /br><强>多洛尔坐< /strong>,依此类推"
as a result it results my_content = 'lorem' instead of -which i'd like to see- ' lorem < br >ipsum< /br> < strong > dolor sit < /strong > and so on'
我如何将内容读为'lorem< br> ipsum< /br><强>多洛尔坐< /strong>等等?
How can i read the content as ' lorem < br>ipsum< /br> < strong > dolor sit < /strong > and so on'?
注意:内容标签可能具有其他html标签,而不是强标签.而且可能根本没有.
Note: content tag may have another html tags instead of strong. And may not have them at all.
推荐答案
from lxml import etree
root = etree.fromstring('''<xml>
<maintag>
<content> lorem <br>ipsum</br> <strong> dolor sit </strong> and so on </content>
</maintag>
</xml>''')
for content in root.xpath('.//maintag/content'):
print etree.tostring(content)
打印
<content> lorem <br>ipsum</br> <strong> dolor sit </strong> and so on </content>
....
for content in root.xpath('.//maintag/content'):
print ''.join(child if isinstance(child, basestring) else etree.tostring(child)
for child in content.xpath('*|text()'))
打印
lorem <br>ipsum</br> <strong> dolor sit </strong> and so on and so on
这篇关于使用xml标记内的html标记进行lxml xml解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!