【问题标题】:lxml xml parsing with html tags inside xml tagslxml xml解析与xml标签内的html标签
【发布时间】:2013-11-19 02:08:26
【问题描述】:
<xml>
<maintag>    
<content> lorem <br>ipsum</br> <strong> dolor sit </strong> and so on </content>
</maintag>
</xml>

我经常解析的 xml 文件,可能在内容标签内有 HTML 标签,如上所示。

我是如何解析文件的:

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' 而不是 -which i'd like to see-' lorem ipsum dolor sit 等等'

如何将内容读为'lorem
ipsumdolor sit等'?

注意:内容标签可能有另一个html标签而不是strong。而且可能根本没有。

【问题讨论】:

  • HTML 标签只是名称与 HML 标签相同的 XML 标签。这不会使它们成为 HTML。例如,在 HTML 中,&lt;br /&gt; 标记为 empty

标签: python html xml xml-parsing lxml


【解决方案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)

打印

<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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多