Skip to main content
 首页 » 编程设计

python之在 xml 标签的文本元素中提取标签

2024年11月01日12myhome

假设我有一个如下形式的 XML 文档

<root> 
  <foos> 
    <foo>the quick <bar>brown </bar>fox</foo> 
  </foos> 
  <!-- Lots more <foo></foo> --> 
</root> 

如何提取全文字符串 the quick fox 以及字符串 brown?

import xml.etree.ElementTree as ET 
doc = ET.parse(xmldocument).getroot() 
foos = doc.find('foos') 
for foo in foos: 
    print foo.text # This will print 'the quick ' 

不确定如何解决这个问题。

请您参考如下方法:

您也可以尝试这样的操作,它会自动迭代所有嵌套标签:

foos = doc.find('foos') 
for foo in foos: 
    for text in foo.itertext(): 
        print text.strip(), 
    print