问题
<xml>
<maintag>
<content> lorem <br>ipsum</br> <strong> dolor sit </strong> and so on </content>
</maintag>
</xml>
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
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'
How can i read the content as ' lorem < br>ipsum< /br> < strong > dolor sit < /strong > and so on'?
Note: content tag may have another html tags instead of strong. And may not have them at all.
回答1:
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)
prints
<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()'))
prints
lorem <br>ipsum</br> <strong> dolor sit </strong> and so on and so on
来源:https://stackoverflow.com/questions/19835784/lxml-xml-parsing-with-html-tags-inside-xml-tags