Hello Guys, Hope you all doing well !!!..
Today I am going to share an example of Xml Read, writer and Delete functionality based on query. Yes!!!..
Just like Sql DB query you can also read write and delete a particular XML File Tag. It is done by Using XPath Xml Reader in Java. And It is quite useful for Large XML File in which a particular Node Element Tag have to read, write and Update. XPath is a language for finding information in an XML file. You can say that XPath is (sort of) SQL for XML files. XPath is used to navigate through elements and attributes in an XML document. You can also use XPath to traverse through an XML file in Java.
Here is the a sample xml file and we are going use it for this example:-
First, we need to create a document builder using DocumentBuilderFactory class. Once we have a document builder object. We uses it to parse XML file and create a document object.Once we have document object. We are ready to use XPath. Just create an xpath object using XPathFactory.
please following the online comment in code for better understanding..
This is all about read write and delete xml by using Xpath in java. You have to copy and paste above code in Java class and create a xml file by using given xml file. you can check more on Xpath in java by using following link :-
Today I am going to share an example of Xml Read, writer and Delete functionality based on query. Yes!!!..
Just like Sql DB query you can also read write and delete a particular XML File Tag. It is done by Using XPath Xml Reader in Java. And It is quite useful for Large XML File in which a particular Node Element Tag have to read, write and Update. XPath is a language for finding information in an XML file. You can say that XPath is (sort of) SQL for XML files. XPath is used to navigate through elements and attributes in an XML document. You can also use XPath to traverse through an XML file in Java.
Here is the a sample xml file and we are going use it for this example:-
<?xml version="1.0"?>
<Employees>
<Employee emplid="1030" type="admin">
<firstname>Saurabh</firstname>
<lastname>Sharma</lastname>
<age>28</age>
<email>saurabh.sharma569@gmail.com</email>
</Employee>
<Employee emplid="1040" type="admin">
<firstname>Sherlock</firstname>
<lastname>Homes</lastname>
<age>32</age>
<email>sherlock@sh.com</email>
</Employee>
<Employee emplid="1050" type="user">
<firstname>Anup Kumar</firstname>
<lastname>Singh</lastname>
<age>26</age>
<email>aone_anup33@gmail.com</email>
</Employee>
<Employee emplid="1060" type="user">
<firstname>Super Man</firstname>
<lastname>Holmes</lastname>
<age>31</age>
<email>super_man@sh.com</email>
</Employee>
<Employee emplid="1070" type="user">
<firstname>Himat Singh</firstname>
<lastname>Negi</lastname>
<age>31</age>
<email>negi_himat@yopmail.com</email>
</Employee>
<Employee emplid="1080" type="user">
<firstname>RaajVir Singh</firstname>
<lastname>Raghuvansi</lastname>
<age>41</age>
<email>rajvir@yopmail.com</email>
</Employee>
</Employees>
In order to understand XPath, first we need to understand basics of DOM parsing in Java. Java provides powerful implementation of domparser.First, we need to create a document builder using DocumentBuilderFactory class. Once we have a document builder object. We uses it to parse XML file and create a document object.Once we have document object. We are ready to use XPath. Just create an xpath object using XPathFactory.
please following the online comment in code for better understanding..
package com.sks.mks;
import java.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
import java.io.IOException;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
importjavax.xml.parsers.ParserConfigurationException;
importjavax.xml.transform.Transformer;
importjavax.xml.transform.TransformerConfigurationException;
importjavax.xml.transform.TransformerException;
importjavax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
importjavax.xml.transform.dom.DOMSource;
importjavax.xml.transform.stream.StreamResult;
importjavax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
importjavax.xml.xpath.XPathExpressionException;
importjavax.xml.xpath.XPathFactory;
importorg.w3c.dom.DOMException;
importorg.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
importorg.w3c.dom.NodeList;
importorg.xml.sax.SAXException;
public class XpathXmlExample {
FileInputStream file = null;
DocumentBuilderFactory builderFactory = null;
DocumentBuilder builder = null;
Document xmlDocument = null;
XPath xPath = null;
//created document builder object.
//We uses it to parse XML file and create a document object
//Once we have document object. We are ready to use XPath.
//Just create an xpathobject using XPathFactory.
public XpathXmlExample() {
try{
file = new FileInputStream(new File("C:/Users/Abc/Desktop/employee_detail.xml"));
builderFactory = DocumentBuilderFactory.newInstance();
builder = builderFactory.newDocumentBuilder();
xmlDocument = builder.parse(file);
xPath = XPathFactory.newInstance().newXPath();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//1. Read firstnameof all employees
newXpathXmlExample().readFistNameOfEmployees("/Employees/Employee/firstname");
//2.Read a specific employee using employee id
newXpathXmlExample().readSpecificEmployeeById("/Employees/Employee[@emplid='1030']");
//3. Read firstnameof all employees who are admin
newXpathXmlExample().readAdminEmployee("/Employees/Employee[@type='admin']/firstname");
//4. Delete an Employee based on Id
newXpathXmlExample().deleteOldTags("/Employees/Employee[@emplid='1080']");
//4. Write an new Employee Detail based on Id
newXpathXmlExample().writeNewTags("/Employees/Employee[@emplid='1080']", "firstname", "Himanshu", "lastname", "Kumar", "age", "32", "email", "himashu.45@yopmail");
}
public voidreadFistNameOfEmployees(String expression){
System.out.println(expression);
NodeList nodeList = null;
try {
nodeList = (NodeList)xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
} catch(XPathExpressionException e) {
e.printStackTrace();
}
}
public voidreadSpecificEmployeeById(String expression){
System.out.println(".....................................");
System.out.println(expression);
Node node = null;
NodeList nodeList = null;
try {
node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
if(null != node) {
nodeList = node.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE)
System.out.println(nodeList.item(i).getNodeName() + " : "+ nod.getFirstChild().getNodeValue());
}
}
} catch(XPathExpressionException e) {
e.printStackTrace();
}
}
public voidreadAdminEmployee(String expression){
System.out.println("*************************");
System.out.println(expression);
NodeList nodeList;
try {
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
nodeList.item(i).getLastChild().getNodeValue();
}
} catch(XPathExpressionException e) {
e.printStackTrace();
}
}
public void writeNewTags(String expression, String Val_1_Name, String Val_1_value, String Val_2_Name, String Val_2_value,String Val_3_Name,String Val_3_value,String Val_4_Name,String Val_4_value){
try{
System.out.println("-----------------------------------------------------");
System.out.println(expression);
Node node2 = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
if(null != node2) {
Element EmployeeFisrtName = xmlDocument.createElement(Val_1_Name);
EmployeeFisrtName.appendChild(xmlDocument.createTextNode(Val_1_value));
Element EmployeeLastName = xmlDocument.createElement(Val_2_Name);
EmployeeLastName.appendChild(xmlDocument.createTextNode(Val_2_value));
Element EmployeeAge = xmlDocument.createElement(Val_3_Name);
EmployeeAge.appendChild(xmlDocument.createTextNode(Val_3_value));
Element EmployeeEmail = xmlDocument.createElement(Val_4_Name);
EmployeeEmail.appendChild(xmlDocument.createTextNode(Val_4_value));
node2.appendChild(EmployeeFisrtName);
node2.appendChild(EmployeeLastName);
node2.appendChild(EmployeeAge);
node2.appendChild(EmployeeEmail);
try {
// write the DOM object to the file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(xmlDocument);
StreamResult streamResult = new StreamResult(new File("C:/Users/Abc/Desktop/employee_detail.xml"));
transformer.transform(domSource, streamResult);
System.out.println("The XML File was updated");
} catch(TransformerConfigurationException e) {
e.printStackTrace();
} catch(TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch(TransformerException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
} catch(XPathExpressionException e) {
e.printStackTrace();
} catch (DOMException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
public void deleteOldTags(String expression){
try{
NodeList nodeList = null;
//expression= "/DisplaySettings/Pages/Page[@PageID='4010']/Sorting/Column";
System.out.println(expression);
Node node2 = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
// at first removing...
if(null != node2) {
nodeList = node2.getChildNodes();
System.out.println("NodeList Size:="+nodeList.getLength());
for (int i = nodeList.getLength() - 1; i >= 0; i--) {
try {
//Element e = (Element)nodeList.item(i);
Node no1 = (Node) nodeList.item(i);
no1.getParentNode().removeChild(no1);
//e.getParentNode().removeChild(e);
} catch(NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
// write the DOM object to the file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(xmlDocument);
StreamResult streamResult = new StreamResult(new File("C:/Users/Abc/Desktop/employee_detail.xml"));
transformer.transform(domSource, streamResult);
System.out.println("The XML File was updated");
} catch(TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
} catch(XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks Happy Coding!!!
0 komentar:
Posting Komentar