通过java代码对pom.xml文件进行操作,首先需要引入jar包:
<!--pom.xml文件解析--><dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId> <version>3.6.0</version></dependency>
1.对xml文件进行增加操作:
代码中的key为:maven-model
Value为:
<dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId> <version>3.6.0</version> </dependency>
/** * xml中添加组件 * @param url 路径 * @param paramKey 组件key * @param paramValue 组件value * @return */ @Override public boolean addXml(String url, String paramKey, String paramValue) { MavenXpp3Reader reader = new MavenXpp3Reader(); String pomUrl = url+"\\pom.xml"; String groupId = ""; String artifactId = ""; String version = ""; //groupId String groupRgex = "<groupId>(.*?)</groupId>"; groupId = getParam(paramValue, groupRgex); //artifactId String artifactRgex = "<artifactId>(.*?)</artifactId>"; artifactId = getParam(paramValue, artifactRgex); //version String versionRgex = "<version>(.*?)</version>"; version = getParam(paramValue, versionRgex); try { FileInputStream fis = new FileInputStream(new File(pomUrl)); Model model = reader.read(fis); List<Dependency> dependencies = model.getDependencies(); Dependency addDependency = new Dependency(); addDependency.setGroupId(groupId); addDependency.setArtifactId(artifactId); addDependency.setVersion(version); dependencies.add(addDependency); model.setDependencies(dependencies); MavenXpp3Writer mavenXpp3Writer = new MavenXpp3Writer(); mavenXpp3Writer.write(new FileWriter(pomUrl),model); } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return true; }
/** * @description 获取匹配模式的正则 * @param param 参数 * @param rgex 正则表达式 * @return */ private String getParam(String param, String rgex) { Pattern groupPattern = Pattern.compile(rgex);// 匹配的模式 Matcher group = groupPattern.matcher(param); String id = ""; while(group.find()){ id = group.group(1); } return id; }
注意:有的<dependency>中不只含有groupId、artifactId、version,需要进行具体分析
2.对xml文件进行删除操作:
/** * 删除xml中依赖 * @param url 路径 * @param paramKey 组件key * @param paramValue 组件value * @return */ @Override public boolean deleteXml(String url, String paramKey, String paramValue) { MavenXpp3Reader reader = new MavenXpp3Reader(); String pomUrl = url+"\\pom.xml"; try { FileInputStream fis = new FileInputStream(new File(pomUrl)); Model model = reader.read(fis); List<Dependency> dependencies = model.getDependencies(); for (Dependency dependency:dependencies) { String artifactId = dependency.getArtifactId(); if(artifactId.equals(paramKey)){ dependencies.remove(dependency); break; } } MavenXpp3Writer mavenXpp3Writer = new MavenXpp3Writer(); mavenXpp3Writer.write(new FileWriter(pomUrl),model); } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return true; }
转自:https://www.cnblogs.com/996--icu/p/13603281.html