lxml xml parsing with html tags inside xml tags

本秂侑毒 提交于 2020-01-05 13:14:13

问题


<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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!