使用ElementTree的根元素混淆

时间:2019-01-14 16:11:25

标签: python-3.x elementtree

我在Python 3.5.1中使用ElementTree。我想解析一个xml文件,例如:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <name>A name</name>
    <groupId>a.group</groupId>
    <artifactId>anArtifact</artifactId>
    <version>1.0</version>
    <packaging>pom</packaging>
    <properties>
        <dependency-version>10.0</dependency-version>
        <another-dependency-version>11.0</another-dependency-version>
    </properties>
</project>

并获取标签 dependency-version 的值。我开始尝试使用以下代码获取属性

mydoc = ElementTree.parse(sources + "pom.xml")
root = mydoc.getroot()
for element in root.findall('properties'):
    print(element)

问题在于,我只得到了根标记 project 及其属性。

>>> root.tag
'{http://maven.apache.org/POM/4.0.0}project'
>>> root.text
'\n    '
>>> root.attrib
{'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': 'http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'}

我也直接尝试了mydoc:

>>> root.findall('project')
[]
>>> mydoc.findall('./properties')
[]
>>> mydoc.findall('./project/properties') 
[]

我了解到 getroot()会给我项目标签,从那里我可以开始工作,但是看来我做错了。

编辑

我遵循了建议的解决方案,并且得到了

>>> ns
{'sm': 'http://maven.apache.org/POM/4.0.0'}
>>> mydoc.findall('.//sm:properties', ns)
[<Element '{http://maven.apache.org/POM/4.0.0}properties' at 0x0325AA80>]
>>> root.findall('.//sm:properties', ns)
[<Element '{http://maven.apache.org/POM/4.0.0}properties' at 0x0325AA80>]
>>> mydoc.findall('.//sm:properties/dependency-version', ns)
[]

似乎正在发现一些东西,但没有找到标记 properties

的两个元素

1 个答案:

答案 0 :(得分:0)

最后,我从Python ElementTree module: How to ignore the namespace of XML files to locate matching element when using the method "find", "findall"得到了一个想法。 基本上,摆脱命名空间是什么。

import re
import xml.etree.ElementTree as ElementTree

filestring = open("C:/temp/test.xml", "r").read()
xmlwithoutns = re.sub('<project[^>]+', '<project>', filestring, count=1)
tree = ElementTree.fromstring(xmlwithoutns)
value = tree.findall("properties/dependency-version")[0].text