Tuesday, August 11, 2009

Include an addition Tag in XML – Java Source Code

The below simple source code will append a node [address] before a specfic node [telephone] and under specific parent node [employee] of a specific XML.

Company.xml [Input]





/*
* AppendChild.java
*/

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;



/**
*
* @author Snehanshu Chatterjee
*/
public class AppendChild {

/** Creates a new instance of AppendChild */
public AppendChild() {
}

private void appendChildIntoXML(){

}

public static void main(String[] args) {
try{
File xmlDocument = new File("Company.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlDocument);
insertNode(document,xmlDocument);
}catch(Exception e){
e.printStackTrace();
}
}


private static void insertNode(Document doc,File fileDoc){
Node parentNode = doc.getParentNode();
Node officeNode = doc.getElementsByTagName("employee").item(0);
Node telChild = doc.getElementsByTagName("telephone").item(0);
Node addressNode = (Node) doc.createElement("Address");
Node newChild = officeNode.appendChild(addressNode);
officeNode.insertBefore(newChild,telChild);

try {
// create DOMSource for source XML document
Source xmlSource = new DOMSource(doc);
// create StreamResult for transformation result
Result result = new StreamResult(new FileOutputStream(fileDoc));
// create TransformerFactory
TransformerFactory transformerFactory = TransformerFactory.newInstance();
// create Transformer for transformation
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
// transform and deliver content to client
transformer.transform(xmlSource, result);
} catch (TransformerFactoryConfigurationError factoryError) {
// handle exception creating TransformerFactory
System.err.println("Error creating " + "TransformerFactory");
factoryError.printStackTrace();
}catch (TransformerException transformerError) {
System.err.println("Error transforming document");
transformerError.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}

}

}

Run:
set classpath=.
javac AppendChild.java
java AppendChild
pause


Company.XML [Output]:

No comments:

Total Pageviews