开发者

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

开发者 https://www.devze.com 2023-02-07 16:31 出处:网络
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 t

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.


You can try MavenXpp3Reader which is part of maven-model. Sample code:

MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileReader(mypom));


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.


This depends on what you're trying to achieve. If you just want to treat it as an XML with embedded XML files, go with suggestions already offered.

If you are looking to implement some form of Maven functionality into your app, you could try the new aether library. I haven't used it, but it looks simple enough to integrate and should offer Maven functionality with little effort on your part.

BTW, this library is a Maven 3 lib, not Maven 2 (as specified in your tag). Don't know if that makes much difference to you

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号