我想解析嵌套元素。我不介意使用XPath或Element。例如,我想打印的一些值位于:
>>> root[0][0][0][0][0].tag
'{http://www.domain.com/somepath/Schema}element'
>>> root[0][0][0][0][0].text
'findme'
遍历 XML 文档、解析和打印element
值的理想方法是什么?这是我正在使用的架构示例。
<?xml version="1.0" encoding="UTF-8"?>
<data xsi:schemaLocation="http://www.domain.com/somepath/Schema file.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.domain.com/somepath/Schema">
<one stuff0="" stuff1="">
<two stuff0="" stuff1="">
<three>
<four stuff0="234234" stuff1="234324">
<element>findme</element>
</four>
<four stuff0="234234" stuff1="234324">
<element>findme2</element>
</four>
<four stuff0="234234" stuff1="234324">
<element>findme3</element>
</four>
</three>
</two>
</one>
<one stuff0="" stuff1="">
<two stuff0="" stuff1="">
<three>
<four stuff0="234234" stuff1="234324">
<element>findme4</element>
</four>
<four stuff0="234234" stuff1="234324">
<element>findme5</element>
</four>
<four stuff0="234234" stuff1="234324">
<element>findme6</element>
</four>
</three>
</two>
</one>
</data>
我尝试了以下方法,但没有返回结果。即使这确实有效,它也不会看到根1 [0] 1 [0][0] 下的元素,依此类推:
>>> for tagname in root[0][0][1][0][0].findall('element'):
... name = tree.get('element')
... print name
...
>>>
根据这个问题,我还尝试了以下方法但没有成功:
>>> for elem in doc.findall('one/two/three/four'):
... print value.get('stuff1'), elem.text
...
>>>
发现问题:
由于缺乏命名空间规范,我在阅读ElementTree 中使用 XPath 的需要帮助后了解到该元素没有被读取。所以下面的例子有效:
>>> import xml.etree.cElementTree as ET
>>> for event, element in ET.iterparse("schema.xml"):
... if element.tag == "{http://www.domain.com/somepath/Schema}element":
... print element.text
...
findme
findme2
findme3
findme4
findme5
findme6