Tuesday, April 15, 2014

XML File Reading, Generation and Modification in Java

Reading:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXML {
public static void main(String arg[]) {
try {
File inputfile = new File(System.getProperty("user.dir") + "\\OR.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docbuilder = dbFactory.newDocumentBuilder();
Document doc = docbuilder.parse(inputfile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodelist = doc.getElementsByTagName("Object");
System.out.println("##################################");
for (int tmp = 0; tmp < nodelist.getLength(); tmp++) {
Node nNode = nodelist.item(tmp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("object name : " + eElement.getAttribute("name"));
System.out.println(
"propertytype : " + eElement.getElementsByTagName("propertytype").item(0).getTextContent());
System.out.println("propertyvalue: "
+ eElement.getElementsByTagName("propertyvalue").item(0).getTextContent());
System.out.println("--------------------------------------");
}
}
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
}
}
 

Generation:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLFileGeneration {

public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("suite");
doc.appendChild(rootElement);
Attr attributeSuite = doc.createAttribute("name");
attributeSuite.setValue("Suite");
rootElement.setAttributeNode(attributeSuite);
attributeSuite = doc.createAttribute("parallel");
attributeSuite.setValue("none");
rootElement.setAttributeNode(attributeSuite);
// staff elements
Element test = doc.createElement("test");
rootElement.appendChild(test);
// set attribute to staff element
Attr attr = doc.createAttribute("name");
attr.setValue("Test");
test.setAttributeNode(attr);
attr = doc.createAttribute("preserve-order");
attr.setValue("true");
test.setAttributeNode(attr);
// firstname elements
Element classes = doc.createElement("classes");
test.appendChild(classes);
// lastname elements
Element class1 = doc.createElement("class");
classes.appendChild(class1);
attr = doc.createAttribute("name");
attr.setValue("com.abc.testscript.javafile");
class1.setAttributeNode(attr);
// nickname elements methods
Element methods = doc.createElement("methods");
class1.appendChild(methods);
// lastname elements
Element include = doc.createElement("include");
methods.appendChild(include);
attr = doc.createAttribute("name");
attr.setValue("MethodName");
include.setAttributeNode(attr);
Element listeners = doc.createElement("listeners");
rootElement.appendChild(listeners);
Element listener = doc.createElement("listener");
listeners.appendChild(listener);
attr = doc.createAttribute("class-name");
attr.setValue("com.abc.listener.TestListener");
listener.setAttributeNode(attr);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(System.getProperty("user.dir") + "/testNG.xml"));
// Output to console for testing
transformer.transform(source, result);
System.out.println(" XML File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}

Modification:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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.NodeList;
import org.xml.sax.SAXException;

public class ModifyXMLFile {

public static void main(String[] args) {
String filePath = "employee.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();

// update attribute value
updateAttributeValue(doc);
// update Element value
updateElementValue(doc);
// delete element
deleteElement(doc);
// add new element
addElement(doc);

// write the updated document to file or console
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("employee_updated.xml"));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("XML file updated successfully");

} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {

e1.printStackTrace();

}
}

private static void addElement(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
Element salaryElement = doc.createElement("salary");
salaryElement.appendChild(doc.createTextNode("10000"));
emp.appendChild(salaryElement);
}
}

private static void deleteElement(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
Node genderNode = emp.getElementsByTagName("gender").item(0);
emp.removeChild(genderNode);
}
}

private static void deleteNodes(Document doc) {
NodeList steps = doc.getElementsByTagName("Employee");
for (int i = 0; i < steps.getLength(); i++) {
Node node = steps.item(i);
node.getParentNode().removeChild(node);
}
}

private static void deleteChildNodes(Document doc) {
NodeList steps = doc.getElementsByTagName("Employee");
for (int i = 0; i < steps.getLength(); i++) {
Node node = steps.item(i);
NodeList nList = node.getChildNodes();
for (int j = 0; j < nList.getLength(); j++) {
Node cnode = nList.item(j);
cnode.getParentNode().removeChild(cnode);
}
}
}

private static void updateElementValue(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
Node name = emp.getElementsByTagName("name").item(0).getFirstChild();
name.setNodeValue(name.getNodeValue().toUpperCase());
}
}

private static void updateAttributeValue(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
String gender = emp.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue();
if (gender.equalsIgnoreCase("male")) {
// prefix id attribute with M
emp.setAttribute("id", "M" + emp.getAttribute("id"));
} else {
// prefix id attribute with F
emp.setAttribute("id", "F" + emp.getAttribute("id"));
}
}
}

}

No comments:

Post a Comment