Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a xml node as first child in another xml document in java?

for eg. root=

<root>
  <param value="abc">
  <param value="bc">
</root>

NodeToInsert could be

<insert><parameterDesc>afds</parameterDesc></insert>

The output should be:

<root>
  <insert><parameterDesc>afds</parameterDesc></insert>
  <param value="abc">
  <param value="bc">
</root>  
like image 737
Jagadesh Avatar asked Jan 22 '23 22:01

Jagadesh


1 Answers

I'll be really irritated if it turns out I just did your homework for you.

package com.akonizo.examples;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;

public class XmlInsertExample {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String initial = "<root><param value=\"abc\"/><param value=\"bc\"/></root>";

        try {
            // Parse the initial document
            ByteArrayInputStream is = new ByteArrayInputStream(initial.getBytes());
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(is);

            // Create the new xml fragment
            Text a = doc.createTextNode("afds");
            Node p = doc.createElement("parameterDesc");
            p.appendChild(a);
            Node i = doc.createElement("insert");
            i.appendChild(p);
            Element r = doc.getDocumentElement();
            r.insertBefore(i, r.getFirstChild());
            r.normalize();

            // Format the xml for output
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            // initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);

            System.out.println(result.getWriter().toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The result will be:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
  <insert>
    <parameterDesc>afds</parameterDesc>
  </insert>
  <param value="abc"/>
  <param value="bc"/>
</root>
like image 98
Craig Trader Avatar answered Jan 29 '23 20:01

Craig Trader