holegeek
holegeek

Reputation: 107

How to merge two XML files with Maven?

i would like to merge two xml files during the execution of the pom.xml.

File 1 :

<A>
 <B/>
</A>

File 2 :

<A>
 <C/>
</A>

Result file :

<A>
 <B/>
 <C/>
</A>

What plugin can i use ?

Thank a lot !

Upvotes: 3

Views: 3192

Answers (1)

Karthik Prasad
Karthik Prasad

Reputation: 10004

Yo can use below code to merge two xml file at specified xpath root is the xml to which you need to merge another xml. insertDoc is the document which you need to add/you can even pass node. And xpath is path of the xml where you need to add the second xml.

public void generateDocument(Document root, Document insertDoc, String xpath) {

        if (null != root) {

            Node element = insertDoc.getDocumentElement();
            Node dest = root.importNode(element, true);

            try {
                Node node = getNode(root, xpath);
                node.insertBefore(dest, null);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(ProcessXML.class.getName()).log(Level.SEVERE,
                        null, ex);
            } catch (SAXException ex) {
                Logger.getLogger(ProcessXML.class.getName()).log(Level.SEVERE,
                        null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ProcessXML.class.getName()).log(Level.SEVERE,
                        null, ex);
            } catch (XPathExpressionException ex) {
                Logger.getLogger(ProcessXML.class.getName()).log(Level.SEVERE,
                        null, ex);
            }

        }

And you can use exec-maven-plugin to execute java code refer usage of plugin here

Upvotes: 3

Related Questions