使用 python 创建循环以在 pom.xml 文件中查找依赖项

create loop to find dependencies in pom.xml file using python

我正在使用 python 创建一个函数,它可以接受任何 pom.xml 文件,然后 return 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 具有不同数量依赖项的文件,所以我认为它必须是一个循环。基于其他 Whosebug 响应,我想出的东西如下。

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)

有没有办法以类似于此的方式将其获取到 return 包含依赖项及其信息的嵌套字典?

dependencyInfo = { 'junit': {'artifactId': 'junit', 'version': '4.8.2'},
                'abc': {'artifactId': 'def', 'version': '4.8.3'}}

这可以通过使用几个库来完成:

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'}})