2017-08-10 85 views
1

我在XML文件中的一些文本标签(PDF利用popplers-utils的pdftohtml转换为XML),看起来像这样:如何使用xml.dom中的minidom将内容作为字符串获取?

<text top="525" left="170" width="603" height="16" font="1">..part of old large book</text> 
<text top="546" left="128" width="645" height="16" font="1">with many many pages and some <i>italics text among 'plain' text</i> and more and more text</text> 
<text top="566" left="128" width="642" height="16" font="1">etc...</text> 

,我可以得到文本envolved与此示例代码文本标签:

import string 
from xml.dom import minidom 
xmldoc = minidom.parse('../test/text.xml') 
itemlist = xmldoc.getElementsByTagName('text') 

some_tag = itemlist[node_index] 
output_text = some_tag.firstChild.nodeValue 
# if there is all text inside <i> I can get it by 
output_text = some_tag.firstChild.firstChild.nodeValue 

# but no if <i></i> wrap only one word of the string 

,但我不能得到“的nodeValue”,如果它里面的内容另一标签(<i> or <b>...),无法获得任何对象

什么是让所有的文字像JavaScript的innerHTML的方法或再普通字符串的最佳方式诅咒儿童标签,即使他们包装一些单词而不是整个nodeValue?

感谢

回答

0

**问:

def getText(nodelist): 
    # Iterate all Nodes aggregate TEXT_NODE 
    rc = [] 
    for node in nodelist: 
     if node.nodeType == node.TEXT_NODE: 
      rc.append(node.data) 
     else: 
      # Recursive 
      rc.append(getText(node.childNodes)) 
    return ''.join(rc) 


xmldoc = minidom.parse('../test/text.xml') 
nodelist = xmldoc.getElementsByTagName('text') 

# Iterate <text ..>...</text> Node List 
for node in nodelist: 
    print(getText(node.childNodes)) 

输出:如何使用minidom命名

这是一个递归的解决方案,例如让内部内容串

..part of old large book 
with many many pages and some italics text among 'plain' text and more and more text 
etc... 

测试使用Python 3.4.2

相关问题