JAXB 解组 - pom.xml

Ram*_*Ram 2 java xml jaxb

我正在开发一个简单的实用程序,用于验证开发人员添加到 pom.xml 的内容。例如,可能存在限制,即所有依赖项版本必须由父 pom 管理,并且如果开发人员向其中一个子项目中的依赖项添加版本标记,则该实用程序应该捕获它。为此,我试图将 pom.xml 的内容加载到 maven 模型类“org.apache.maven.model.Model”中。但是,我收到此异常:

unexpected element (uri:"http://maven.apache.org/POM/4.0.0", local:"project"). Expected elements are (none)
Run Code Online (Sandbox Code Playgroud)

添加自定义验证处理程序以忽略“意外元素”异常(实际上,始终返回 true)不起作用。这是我的代码:

public static void main(String[] args) {
    try {
        unmarshalXMLToObject(new File("pom.xml"));
    } catch (Exception e) {
        e.printStackTrace();
    } 
}


public static Model unmarshalXMLToObject(File xmlFileToUnmarshal) throws JAXBException, SAXException, IOException,
        ParserConfigurationException {

    JAXBContext jaxbContext = JAXBContext.newInstance(Model.class);

    Unmarshaller m = jaxbContext.createUnmarshaller();

    m.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent arg0) {
            // return true always
            return true;
        }
    });

    @SuppressWarnings("unchecked")
    Model objectToReturn = (Model) m.unmarshal(xmlFileToUnmarshal);

    return objectToReturn;
}
Run Code Online (Sandbox Code Playgroud)

我还尝试将 maven-4.0.0.xsd 添加到解组器中,但这也无济于事。

Ram*_*Ram 5

结果证明我根本不需要使用 JAXB 解组。

下面的一段代码做到了,至少对于我想要的。

org.apache.maven.model.io.xpp3.MavenXpp3Reader mavenreader = new MavenXpp3Reader();

org.apache.maven.model.Model model = mavenreader.read(new FileReader(pomXml));
Run Code Online (Sandbox Code Playgroud)

有了这个,我就有了完整的 maven pom.xml 作为 java 类。

我猜标题中 JAXB 的存在和标签拒绝了这个问题的潜在回答者。