使用ElementTree进行Python XML解析:findall重新调整空列表

时间:2019-03-15 03:12:43

标签: python xml

我的XML这样开始:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="define2-0-0.xsl"?>
<ODM
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns="http://www.cdisc.org/ns/odm/v1.3"
  xmlns:def="http://www.cdisc.org/ns/def/v2.0"
  xmlns:nciodm="http://ncicb.nci.nih.gov/xml/odm/EVS/CDISC"
  ODMVersion="1.3.2"
  FileType="Snapshot"
  FileOID="SDTM-Terminology-2015-06-26.odm.xml.."
  CreationDateTime="2016-08-30T16:37:21">
    <Study OID="SDTM-Terminology-2015-06-26.odm.xml..">
    ...it goes on from there

我可以将其解析为ELementTree对象:

import xml.etree.ElementTree as ET
root = tree.getroot()

此代码:

for child in root:
    print "Child of root:  " + child.tag

产生:

Child of root:  {<some url>}Study

我需要遍历树的多个级别,并且我不想使用7-8个嵌套的“ for child in ...”循环。我想使用XMLPath,但是我什么都无法工作。这段代码:

for node in tree.findall('./Study')
    print(node.tag)

不返回任何内容。我不能让它返回任何东西。我尝试过

for node in root.findall('./Study')
    print (node.tag)

,它也不会产生任何结果。我已经尝试了根与树的各种组合,无论是否带有前导“ ./”。我什么都不能工作。这是我第一次使用ElementTree。有人能帮我吗?

0 个答案:

没有答案