使用elemen从elemen子文档获取属性

2024-09-28 15:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xml pom文件,如下所示:

<?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>
<parent>
    <groupId>com.amirsys</groupId>
    <artifactId>components-parent</artifactId>
    <version>RELEASE</version>
</parent>
<artifactId>statdxws</artifactId>
<version>6.5.0-16</version>
<packaging>war</packaging>
<dependencies>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1200-jdbc41</version>
        <scope>provided</scope>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.amirsys</groupId>
        <artifactId>referencedb</artifactId>
        <version>5.0.0-1</version>
        <exclusions>
            <exclusion>
                <groupId>com.amirsys</groupId>
                <artifactId>jig</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

我试图使用元素树来提取groupid、artifactId和versions来创建一个依赖对象,但是它找不到依赖标记。这是我目前为止的代码:

^{pr2}$

这不会输出任何结果,而且我不明白为什么代码没有遍历依赖标记。任何帮助都将不胜感激。在


Tags: orgcomhttpversionapachexmldependencyparent
1条回答
网友
1楼 · 发布于 2024-09-28 15:15:00

您的XML有一个小错误。应该有一个结束标记</project>,你可能在问题中漏掉了。在

以下是我的工作:

from xml.etree import ElementTree
tree = ElementTree.parse('pomFile.xml')
root = tree.getroot()
namespace = '{http://maven.apache.org/POM/4.0.0}'
for dependency in root.iter(namespace+'dependency'):
    groupId = dependency.find(namespace+'groupId').text
    artifactId = dependency.find(namespace+'artifactId').text
    version = dependency.find(namespace+'version').text
    print groupId, artifactId, version

$ python -i a.py
org.postgresql postgresql 9.4-1200-jdbc41
com.amirsys referencedb 5.0.0-1

您对.get()的使用错误。看看.get()是如何工作的。假设您的xml是:

^{pr2}$

您可以编写如下python代码:

^{3}$

这将打印:

Liechtenstein 1
Singapore 4
Panama 68

如您所见,.get()给出了属性的值。docs对此很清楚。在

相关问题 更多 >