Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a library for reading maven2/3 pom xml files?

I would like to read a pom.xml in Java code. I wonder if there is a library for that, so I can have an iterator for different sections, e.g., dependenes, plugins, etc. I want to avoid to build a parser by hand.

like image 928
Skarab Avatar asked Jan 29 '11 18:01

Skarab


People also ask

How do you read POM xml?

POM is an acronym for Project Object Model. The pom. xml file contains information of project and configuration information for the maven to build the project such as dependencies, build directory, source directory, test source directory, plugin, goals etc. Maven reads the pom.

Where does the POM XML file go?

The pom. xml is placed in the projects root-folder.

Can we have multiple POM xml?

Yes you can use Maven Profiles to manage this. Obviously you can tweak this approach to suit your needs however works best.

What is difference between POM and POM xml?

POM stands for Project Object Model, and it is the core of a project's configuration in Maven. It is a single configuration XML file called pom. xml that contains the majority of the information required to build a project.


1 Answers

Firstly, I'm assuming you are not already running inside a Maven plugin, as there are easier ways to achieve that with the available APIs there.

The MavenXpp3Reader solution posted earlier will allow you to read the POM easily, however does not take into account inheritance of the parent and interpolation of expressions.

For that, you would need to use the ModelBuilder class.

Use of this is quite simple, for example from Archiva is this code fragment:

ModelBuildingRequest req = new DefaultModelBuildingRequest(); req.setProcessPlugins( false ); req.setPomFile( file ); req.setModelResolver( new RepositoryModelResolver( basedir, pathTranslator ) ); req.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );  Model model; try {     model = builder.build( req ).getEffectiveModel(); } catch ( ModelBuildingException e ) {      ... } 

You must do two things to run this though:

  1. instantiate and wire an instance of ModelBuilder including its private fields
  2. use one of Maven's resolvers for finding the parent POMs, or write your own (as is the case in the above snippet)

How best to do that depends on the DI framework you are already using, or whether you want to just embed Maven's default container.

like image 123
Brett Porter Avatar answered Sep 23 '22 01:09

Brett Porter