Home > Software design >  Issue with python script while parsing pom file in project
Issue with python script while parsing pom file in project

Time:03-23

I'm having issue extracting version number using python script. Its returning none while running the script. Can someone help me on this ?

Python Script:

import xml.etree.ElementTree as ET

tree = ET.parse('pom.xml')
root = tree.getroot()
releaseVersion = root.find("version")
print(releaseVersion)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <artifactId>watcher</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <groupId>com.test</groupId>
    <name>file</name>
    <packaging>jar</packaging>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <relativePath/>
        <version>2.6.1</version> 
    </parent>

</project>

CodePudding user response:

You're not taking into account that all of your elements are in a default namespace defined by xmlns="http://maven.apache.org/POM/4.0.0" in your <project> element.

So you have to create your query with this namespace.

import xml.etree.ElementTree as ET    
tree = ET.parse('pom.xml')
root = tree.getroot()
NS = { 'maven' : 'http://maven.apache.org/POM/4.0.0' }
releaseVersion = root.find("maven:version",NS)
print(releaseVersion.text)

Here NS = { ... } defines the namespace (in the following referred to by its prefix maven) used in the following XPath expression.

CodePudding user response:

Your pom.xml has a namespace xmlns="http://maven.apache.org/POM/4.0.0" in the project tag.

If you must search with fullname, you need to follow {namespace}tag

>> root.find("{http://maven.apache.org/POM/4.0.0}version")
<Element '{http://maven.apache.org/POM/4.0.0}version' at 0x0000014635EC0A40>

But if you don't bother you can search with {*}tag

>> root.find("{*}version")
<Element '{http://maven.apache.org/POM/4.0.0}version' at 0x0000014635EC0A40>
  • Related