lxml xml parsing with html tags inside xml tags

2019-08-15 06:58发布

<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条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-15 07:38
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
查看更多
登录 后发表回答