XML – Serializing and deserializing objects using JAVA

Nowadays systems typically have to interchange data with another systems, and the XML (eXtendable Markup Language) is one common pattern for this purpose.

 When we are developing software using Object Oriented Programming languages, the whole program has to handle its datasets based in objects, composed by a set of attributes.

 In this context it is very important to know how parsing XML documents, that essentially are plain text documents into objects, to then the program can operate with its data independently from its data source.

We are going to see here how to create a XML document based on objects using the JAVA programming language. This example utilizes only native classes, so no external library is necessary.

 

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
//create root node
Element rootTag = doc.createElement("people");//root tag
//create child node
Person p= new Person("Frodo Baggins","frodo.baggins@mail.lor","004109283624");
Element firstLevel = doc.createElement("person");
firstLevel.setAttribute(
"name", p.getName());
firstLevel.setAttribute(
"email", p.getEmail());
firstLevel.setAttribute(
"phone", p.getPhone());
//firstLevel.setTextContent("Text content of a tag element");
//append child node to root node
rootTag.appendChild(firstLevel);

//add a second object
p= new Person("Samwise Gamgee","samwise.gamgee@mail.lor","004109285457");
firstLevel = doc.createElement(
"person");
firstLevel.setAttribute(
"name", p.getName());
firstLevel.setAttribute(
"email", p.getEmail());
firstLevel.setAttribute(
"phone", p.getPhone());
//append child node to root node
rootTag.appendChild(firstLevel);

//append root with complete tree to Document
doc.appendChild(rootTag);

 

At this point the doc variable contains the whole XML document in memory, using the DOM (Document Object Model) structure, so, the next step is to convert this variable into a XML String. The code below will parse the doc variable into a String and write it to local file.



//convert XML Document to a string
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource domSource = new DOMSource(doc);
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
Log.i("XML",sw.toString());
//write XML string to the disk
File file = new File(this.getApplicationContext().getFilesDir(), "xml_object.xml");
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
dos.write(sw.toString().getBytes());
dos.close();
fos.close();


Now we are in the another hand. We have the plain text XML document and the need is to parse that back to objects in our high level programming language. Basically we have to filter the tags/nodes we have to process, and from them extract the data, instantiating objects and assigning values to its attributes.



//Read XML file
DocumentBuilderFactory dbFactoryRead = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilderRead = null;
try {
    dBuilderRead =
dbFactoryRead.newDocumentBuilder();
}
catch (ParserConfigurationException e) {
    e.printStackTrace();
}
Document docRead = null;
InputStream is= new FileInputStream(file);
try {
    doc =
dBuilder.parse(is);
}
catch (Exception e) {
    e.printStackTrace();
}
NodeList nList = doc.getElementsByTagName("people");
for (int i = 0; i < nList.getLength(); i++) {
   
NodeList childrenTags=nList.item(i).getChildNodes();
   
int childrenTagsCount=childrenTags.getLength();
   
Log.i("XML","Children count:"+childrenTagsCount);
   
for(byte j=0;j<childrenTagsCount;j++) {
       
if(childrenTags.item(j).getNodeName().equals("#text")) continue;
       
Log.i("XML", "XML - node name:" + childrenTags.item(j).getNodeName());
       
Log.i("XML", "XML - node text content:" + childrenTags.item(j).getTextContent());
       
Log.i("XML", "XML - node attribute read:" +childrenTags.item(j).getAttributes().getNamedItem("name").getTextContent() );
       
Log.i("XML", "XML - node attribute read:" +childrenTags.item(j).getAttributes().getNamedItem("email").getTextContent() );
       
Log.i("XML", "XML - node attribute read:" +childrenTags.item(j).getAttributes().getNamedItem("phone").getTextContent() );
    }
}

 

The whole code is available to be downloaded here: https://github.com/rafaelqg/code/blob/main/FileHandler_XML_JSON.java

 

You may watch a video classes about this topic here:

 


The imported classes were:

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
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.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

  

Comments

Popular posts from this blog

HASHLIB: Using HASH functions MD5 and SHA256

Spread Operator

Dart: implementing Object Oriented Programming (OOP)