我正在尝试使用apache maven模型(https://maven.apache.org/ref/3.5.0/apidocs/org/apache/maven/model/package-summary.html)修改pom文件,但无法保存注释。
我尝试了xmlstarlet cmd工具,该工具可以保留注释,但是对于我来说,它很慢,因为我要修改100个pom文件。
这是我正在尝试的示例pom文件,
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>test-java-dependencies</artifactId>
<version>1.2.2</version>
<packaging>pom</packaging>
<properties>
<!--################################################-->
<!-- Define and set: -->
<!-- * general project settings -->
<!-- * plugin versions and settings -->
<!-- * dependency versions and settings -->
<!--################################################-->
<version.jackson>2.9.9</version.jackson>
</properties>
<dependencyManagement>
<dependencies>
<!-- Jackson all related libraries imported -->
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-bom</artifactId>
<version>${version.jackson}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
这是Java代码,
File pomFile = new File(".....\\pom.xml");
Model model = getMavenModel(pomFile);
model.setVersion("1.2.3")
File pomFileNew = new File("...\\pom-new.xml");
writeMavenModel(model, pomFile1);
static Model getMavenModel(File file) {
MavenXpp3Reader reader = new MavenXpp3Reader();
reader.setAddDefaultEntities(true);
try {
return reader.read(new FileReader(file));
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
static void writeMavenModel(Model model, File file) {
MavenXpp3Writer writer = new MavenXpp3Writer();
try (FileWriter w = new FileWriter(file)) {
writer.write(w, model);
} catch (IOException e) {
e.printStackTrace();
}
}
我不仅在设置版本,还进行了一些修改。
Apache Maven模型是否支持保留评论?我搜索了一段时间,但无法确认。 Java中是否有任何库可以做到这一点?