1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Python,Java]pom.xmlからMaven依存ライブラリ一覧を取得する方法 メモ

Posted at
  • Java/Mavenプロジェクト開発の際に、pom.xmlファイルから依存ライブラリの一覧をcsv形式で取得したかった。
  • 取得用のPythonスクリプトを作成したため、メモとして残しておく。

事前準備

  • ライブラリインストール
pip3 install lxml
  • テスト用pom.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.example.test</groupId>
	<artifactId>test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>test</name>
	<dependencies>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.10</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.8</version>
		</dependency>
	</dependencies>
</project>

スクリプト

  • extract_dependencies_from_pom.py
from lxml import etree

def extractDependenciesFromPom():
    # 出力ファイル
    output = "./dependencies_from_pom.csv"
    f = open(output, "w")

    # 出力ファイルヘッダー 書き込み
    header_string = "groupId,artifactId,version"+"\n"
    f.write(header_string)
    # pom.xml 読み込み
    tree = etree.parse("./pom.xml")
    root = tree.getroot()
    dependencies = root.find('./{*}dependencies')
    for dependency in dependencies:
        # dependency内の各要素を取得
        groupId = dependency.find('./{*}groupId').text
        artifactId = dependency.find('./{*}artifactId').text
        version = dependency.find('./{*}version').text

        # CSV 書き込み
        output_string = groupId \
                            + "," + artifactId \
                            + "," + version +"\n"
        print(output_string)
        f.write(output_string)
    f.close

extractDependenciesFromPom()

動作確認

※extract_dependencies_from_pom.pyとpom.xmlを同一フォルダに配置する。

  • 実行

    python3 extract_dependencies_from_pom.py
    
  • 出力結果

    groupId,artifactId,version
    commons-codec,commons-codec,1.10
    com.fasterxml.jackson.core,jackson-databind,2.9.8
    

参考情報

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?