Passion of IT

JAVA XML Processing

Xml or extended markup language is a markup language made of many tag which are both readable by humans and machine, it has a tree structure with a root node, many branches and leaves.

Xml can respect a set of rules defined in two ways: the old DTD (Document Type Definition) and the more recent XML schema.

XML is useful for the below purposes

 

the only problem of the xml is that it’s redundant so every opened tag should be closed and the tag name is replicated two times


<tag_name>
tag value
<tag_name>

if the tag name is huge and it has not value so we transmit on line many characters with no value

A better format is the JSON which can be converted to an object but it replaces tags with parenthesis, so it’s not replicated any information.

How to process an XML file using Java?

We need to parse it using XPath and to add a node everywhere.

 

XPATH

let’s try to inquire the below xml


<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Employee id="1">
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</Employee>
<Employee id="2">
<age>35</age>
<name>Lisa</name>
<gender>Female</gender>
<role>CEO</role>
</Employee>
<Employee id="3">
<age>40</age>
<name>Tom</name>
<gender>Male</gender>
<role>Manager</role>
</Employee>
<Employee id="4">
<age>25</age>
<name>Meghna</name>
<gender>Female</gender>
<role>Manager</role>
</Employee>
</Employees>


private static List<String> getFemaleEmployeesName(Document doc, XPath xpath) {
List<String> list = new ArrayList<>();
try {
//create XPathExpression object
XPathExpression expr =
xpath.compile("/Employees/Employee[gender='Female']/name/text()");
//evaluate expression result on XML document
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
list.add(nodes.item(i).getNodeValue());
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
}

private static List<String> getEmployeeNameWithAge(Document doc, XPath xpath, int age) {
List<String> list = new ArrayList<>();
try {
XPathExpression expr =
xpath.compile("/Employees/Employee[age>" + age + "]/name/text()");

NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++)
list.add(nodes.item(i).getNodeValue());
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
}

private static String getEmployeeNameById(Document doc, XPath xpath, int id) {
String name = null;
try {
XPathExpression expr =
xpath.compile("/Employees/Employee[@id='" + id + "']/name/text()");
name = (String) expr.evaluate(doc, XPathConstants.STRING);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

return name;
}

 

Below is the method to add a node in the name of a female employer


private static List<String> addNodesInsideFemaleEmployeesName(Document doc, XPath xpath) {
List<String> list = new ArrayList<>();
try {
//create XPathExpression object
XPathExpression expr =
xpath.compile("/Employees/Employee[gender='Female']/name/text()");
//evaluate expression result on XML document
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++){

Element node = doc.createElement("New_Node"+i);
Element nodeInside = doc.createElement("newnodeInside");

nodeInside.setTextContent("This is the content"); //adds content
nodeInside.setAttribute("attrib", "attrib_value"); //adds an attribute
node.appendChild(nodeInside);

nodes.item(i).getParentNode().insertBefore(node, nodes.item(i).getNextSibling());
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
}

 

below is the result

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee id="1">
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</Employee>
<Employee id="2">
<age>35</age>
<name>Lisa<New_Node0>
<newnodeInside attrib="attrib_value">This is the content</newnodeInside>
</New_Node0>
</name>
<gender>Female</gender>
<role>CEO</role>
</Employee>
<Employee id="3">
<age>40</age>
<name>Tom</name>
<gender>Male</gender>
<role>Manager</role>
</Employee>
<Employee id="4">
<age>25</age>
<name>Meghna<New_Node1>
<newnodeInside attrib="attrib_value">This is the content</newnodeInside>
</New_Node1>
</name>
<gender>Female</gender>
<role>Manager</role>
</Employee>
</Employees>

if needed to insert the node outside the name it’s necessary just to modify the XPATH query that will be

/Employees/Employee[gender='Female']/name

the project is available here

No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite="
"> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Recent Comments

Michele Rizzithe website doesn't exist. Ara you a robot? In any case it's difficult that an automatic system writes a comment here since there are two captchas...
Hello there! This is kind of off topic but I need some guidance from an established blog. Is it very hard to set up your own blog? I'm not very t...
We are a group of volunteers and opening a new scheme in our community. Your web site offered us with valuable information to work on. You've done a...
March 2024
M T W T F S S
« Dec    
 123
45678910
11121314151617
18192021222324
25262728293031

Login