寻找元素和印刷价值

时间:2013-03-28 03:22:15

标签: python xml xml-parsing

我想解析嵌套元素。我不介意使用XPathElement。例如,我想要打印的一些值是:

>>> 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
...
>>>

根据这个question,我也尝试了以下内容但没有成功:

>>> for elem in doc.findall('one/two/three/four'):
...     print value.get('stuff1'), elem.text
...
>>>

发现问题:

由于缺少我在阅读Need Help using XPath in ElementTree后学到的命名空间规范,因此未读取该元素。以下示例有效:

>>> 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

1 个答案:

答案 0 :(得分:0)

如果没有看到您的XML文档,我无法确定,但我认为您想要做的是:

<强>的test.xml

<?xml version="1.0"?>
<root>
  <group>
    <element>This is the first text</element>
  </group>
  <group>
    <element>This is the second text</element>
  </group>
  <group>
    <element>This is the third text</element>
  </group>
</root>

<强> test.py

import xml.etree.cElementTree as ET

for event, element in ET.iterparse("test.xml"):
    if element.tag == "element":
       print element.text

在我得到的终端中运行这些文件:

mike@tester:~$ python test.py
This is the first text
This is the second text
This is the third text