2013-08-26 35 views
0

我得純文本了XML的節點及其子節點,或者什麼別的,這些奇怪的內標籤是:獲取文本的XML節點包括的childNodes(或像這樣)

例-nodes:

<BookTitle> 
<Emphasis Type="Italic">Z</Emphasis> 
= 63 - 100 
</BookTitle> 

或:

<BookTitle> 
Mtn 
<Emphasis Type="Italic">Z</Emphasis> 
= 74 - 210 
</BookTitle> 

我得:

Z = 63 - 100 
Mtn Z = 74 - 210 

請記住,這只是一個例子! BookTitle-Node中可能有任何類型的「子節點」,我需要的只是BookTitle中的純文本。

我想:

tagtext = root.find('.//BookTitle').text 
print tagtext 

但的.text不能與這個陌生的XML節點處理,並給了我一個 「NoneType」 回

祺&謝謝!

回答

2

這不是BookTitle節點的text,而是Emphasis節點的tail。所以,你應該這樣做:

def parse(el): 
    text = el.text.strip() + ' ' if el.text.strip() else '' 
    for child in el.getchildren(): 
     text += '{0} {1}\n'.format(child.text.strip(), child.tail.strip()) 
    return text 

它給你:

>>> root = et.fromstring(''' 
    <BookTitle> 
    <Emphasis Type="Italic">Z</Emphasis> 
    = 63 - 100 
    </BookTitle>''') 
>>> print parse(root) 
Z = 63 - 100 

併爲:

>>> root = et.fromstring(''' 
<BookTitle> 
Mtn 
<Emphasis Type="Italic">Z</Emphasis> 
= 74 - 210 
</BookTitle>''') 
>>> print parse(root) 
Mtn Z = 74 - 210 

這應該給你一個基本的想法做什麼。

更新:固定的空白......

+0

謝謝,我有錯誤,當尾巴是空或文本是空的,所以我這樣做:'高清解析(EL): 文本=「」 如果el.text: 文本= el.text.strip () 兒童在el.getchildren(): 如果child.text: 文字+ = child.text.strip() 如果child.tail: 文字+ = child.tail.strip() 返回文本 ' 這似乎在工作。如果我可以簡化它,請告訴我:) – dynobo

+0

是的,你必須檢查'tail'或'text'是否爲'None',我忘記包含該檢查。我從你的例子中假設他們將永遠存在。 –

0

可以使用minidom命名解析器。下面是一個示例:

from xml.dom import minidom 

def strip_tags(node): 
    text = "" 
    for child in node.childNodes: 
     if child.nodeType == doc.TEXT_NODE: 
      text += child.toxml() 
     else: 
      text += strip_tags(child) 
    return text 

doc = minidom.parse("<your-xml-file>") 

text = strip_tags(doc) 

strip_tags遞歸函數將瀏覽xml樹並按順序提取文本。