我正在使用python创建一个函数,该函数可以接收任何pom.xml文件,然后从依赖项中返回groupId,artifactId和版本。
我从https://www.javatpoint.com/maven-pom-xml找到了以下pom.xml,以显示我要解析的结构。
<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>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
</dependencies>
.
.
.
<dependencies>
<dependency>
<groupId>abc</groupId>
<artifactId>def</artifactId>
<version>4.8.3</version>
</dependency>
</dependencies>
</project>
我曾经尝试过使用minidom和etree.ElementTree,但是我对所有这些都是全新的,并且无法取得进展。我还希望它能够处理具有不同数量的依赖项的pom.xml文件,因此我认为它必须是一个循环。基于其他stackoverflow响应,下面是我想到的内容。
from xml.dom import minidom
dependencyInfo = {}
dom = minidom.parse('pom.xml')
depend = dom.getElementsByTagName("dependency")
for dep in depend:
info = {}
info['groupId'] = dep.attributes['groupId'].value
info['artifactId'] = dep.attributes['artifactId'].value
info['version'] = dep.attributes['version'].value
dependencyInfo[] = info
print(dependencyInfo)
是否有办法以类似的方式返回包含相关性及其信息的嵌套字典?
dependencyInfo = { 'junit': {'artifactId': 'junit', 'version': '4.8.2'},
'abc': {'artifactId': 'def', 'version': '4.8.3'}}
答案 0 :(得分:1)
这可以通过使用几个库来完成:
pom= """[your xml above]"""
from lxml import etree
from collections import defaultdict
root = etree.fromstring(pom) #or .parse('pom.xml') if you read it from that file
tree = etree.ElementTree(root)
depend = tree.xpath("//*[local-name()='dependency']")
dependencyInfo = defaultdict(dict)
for dep in depend:
infoList = []
for child in dep.getchildren():
infoList.append(child.tag.split('}')[1])
infoList.append(child.text)
dependencyInfo[infoList[1]].update({infoList[2] : infoList[3],infoList[4] : infoList[5]})
dependencyInfo
输出:
defaultdict(dict,
{'junit': {'artifactId': 'junit', 'version': '4.8.2'},
'abc': {'artifactId': 'def', 'version': '4.8.3'}})