Using xml files in java

JAXB Read XML to Java Object Example

Java example to read XML to Objects. XML can be supplied via some .xml file or simply an string representation. The populated Java objects then can be used in application for further processing or workflow.

Java provides many approaches to read an XML file and use the XL content to either print, use in application or populate data in Java objects to further use in application lifecycle. The three main APIs used for this purpose are Simple API for XML ( SAX ), the Document Object Model ( DOM ) and Java Architecture for XML Binding ( JAXB ).

  • SAX or DOM parser use the JAXP API to parse an XML document. Both scan the document and logically break it up into discrete pieces (e.g. nodes, text and comment etc).
  • SAX parser starts at the beginning of the document and passes each piece of the document to the application in the sequence it finds it. Nothing is saved in memory so it can’t do any in-memory manipulation.
  • DOM parser creates a tree of objects that represents the content and organization of data in the Document object in memory. Here, application can then navigate through the tree to access the data it needs, and if appropriate, manipulate it.
  • While JAXB unmarshal the document into Java content objects. The Java content objects represent the content and organization of the XML document, and are directly available to your program.
Читайте также:  Java short default value

2) Convert XML String to Java Object

To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations.

Now get the Unmarshaller instance from JAXBContext . It’s unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.

String xmlString = "" + " " + " 101" + " IT" + " " + " Lokesh" + " 1" + " Gupta" + ""; JAXBContext jaxbContext; try < jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); System.out.println(employee); >catch (JAXBException e) < e.printStackTrace(); >Output: Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

3) Convert XML File to Java Object

Reading XML from file is very similar to above example. You only need to pass File object in place of StringReader object. File will have reference to ‘.xml’ file to be read in file system.

File xmlFile = new File("employee.xml"); JAXBContext jaxbContext; try < jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile); System.out.println(employee); >catch (JAXBException e) < e.printStackTrace(); >Output: Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]
import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "employee") @XmlAccessorType(XmlAccessType.PROPERTY) public class Employee implements Serializable < private static final long serialVersionUID = 1L; private Integer id; private String firstName; private String lastName; private Department department; public Employee() < super(); >public Employee(int id, String fName, String lName, Department department) < super(); this.id = id; this.firstName = fName; this.lastName = lName; this.department = department; >//Setters and Getters @Override public String toString() < return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department="+ department + "]"; >> @XmlRootElement(name = "department") @XmlAccessorType(XmlAccessType.PROPERTY) public class Department implements Serializable < private static final long serialVersionUID = 1L; Integer id; String name; public Department() < super(); >public Department(Integer id, String name) < super(); this.id = id; this.name = name; >//Setters and Getters @Override public String toString() < return "Department [id=" + id + ", name=" + name + "]"; >>

Content of xml file is same as first example.

Читайте также:  Javascript содержимое css файла

Drop me your questions in comments section.

Источник

How to read XML file in Java – (DOM Parser)

java xml dom parser

This tutorial will show you how to use the Java built-in DOM parser to read an XML file.

Note
The DOM Parser is slow and consumes a lot of memory when it reads a large XML document because it loads all the nodes into the memory for traversal and manipulation.

Instead, we should consider SAX parser to read a large size of XML document, SAX is faster than DOM and use less memory.

1. What is Document Object Model (DOM)

The Document Object Model (DOM) uses nodes to represent the HTML or XML document as a tree structure.

Below is a simple XML document:

  yong mook kim mkyong 100000   
  • The is the root element.
  • The , and all are the element nodes.
  • The text node is the value wrapped by the element nodes; for example, yong , the yong is the text node.
  • The attribute is part of the element node; for example, the id is the attribute of the staff element.

2. Read or Parse a XML file

This example shows you how to use the Java built-in DOM parser APIs to read or parse an XML file.

   yong mook kim mkyong 100000  low yin fong fong fong 200000   

2.2 Below is a DOM parser example of parsing or reading the above XML file.

 package com.mkyong.xml.dom; 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; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.io.InputStream; public class ReadXmlDomParser < private static final String FILENAME = "/users/mkyong/staff.xml"; public static void main(String[] args) < // Instantiate the Factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try < // optional, but recommended // process XML securely, avoid attacks like XML External Entities (XXE) dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // parse XML file DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File(FILENAME)); // optional, but recommended // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); System.out.println("Root Element :" + doc.getDocumentElement().getNodeName()); System.out.println("------"); // get NodeList list = doc.getElementsByTagName("staff"); for (int temp = 0; temp < list.getLength(); temp++) < Node node = list.item(temp); if (node.getNodeType() == Node.ELEMENT_NODE) < Element element = (Element) node; // get staff's attribute String // get text String firstname = element.getElementsByTagName("firstname").item(0).getTextContent(); String lastname = element.getElementsByTagName("lastname").item(0).getTextContent(); String nickname = element.getElementsByTagName("nickname").item(0).getTextContent(); NodeList salaryNodeList = element.getElementsByTagName("salary"); String salary = salaryNodeList.item(0).getTextContent(); // get salary's attribute String currency = salaryNodeList.item(0).getAttributes().getNamedItem("currency").getTextContent(); System.out.println("Current Element :" + node.getNodeName()); System.out.println("Staff Id : " + id); System.out.println("First Name : " + firstname); System.out.println("Last Name : " + lastname); System.out.println("Nick Name : " + nickname); System.out.printf("Salary [Currency] : %,.2f [%s]%n%n", Float.parseFloat(salary), currency); >> > catch (ParserConfigurationException | SAXException | IOException e) < e.printStackTrace(); >> > 
 Root Element :company ------ Current Element :staff Staff Id : 1001 First Name : yong Last Name : mook kim Nick Name : mkyong Salary [Currency] : 100,000.00 [USD] Current Element :staff Staff Id : 2001 First Name : low Last Name : yin fong Nick Name : fong fong Salary [Currency] : 200,000.00 [INR] 

3. Read or Parse XML file (Unicode)

In DOM parser, there is no difference between reading a normal and Unicode XML file.

3.1 Review below XML file containing some Chinese characters (Unicode).

   木金 mkyong 100000  low yin fong fong fong 200000   

3.2 The below example parse the above XML file; it loops all the nodes one by one and prints it out.

 package com.mkyong.xml.dom; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; public class ReadXmlDomParserLoop < public static void main(String[] args) < // Instantiate the Factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try (InputStream is = readXmlFileIntoInputStream("staff-unicode.xml")) < // parse XML file DocumentBuilder db = dbf.newDocumentBuilder(); // read from a project's resources folder Document doc = db.parse(is); System.out.println("Root Element :" + doc.getDocumentElement().getNodeName()); System.out.println("------"); if (doc.hasChildNodes()) < printNote(doc.getChildNodes()); >> catch (ParserConfigurationException | SAXException | IOException e) < e.printStackTrace(); >> private static void printNote(NodeList nodeList) < for (int count = 0; count < nodeList.getLength(); count++) < Node tempNode = nodeList.item(count); // make sure it's element node. if (tempNode.getNodeType() == Node.ELEMENT_NODE) < // get node name and value System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]"); System.out.println("Node Value =" + tempNode.getTextContent()); if (tempNode.hasAttributes()) < // get attributes names and values NamedNodeMap nodeMap = tempNode.getAttributes(); for (int i = 0; i < nodeMap.getLength(); i++) < Node node = nodeMap.item(i); System.out.println("attr name : " + node.getNodeName()); System.out.println("attr value : " + node.getNodeValue()); >> if (tempNode.hasChildNodes()) < // loop again if has child nodes printNote(tempNode.getChildNodes()); >System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]"); > > > // read file from project resource's folder. private static InputStream readXmlFileIntoInputStream(final String fileName) < return ReadXmlDomParserLoop.class.getClassLoader().getResourceAsStream(fileName); >> 
 Root Element :company ------ Node Name =company [OPEN] Node Value = 揚 木金 mkyong 100000 low yin fong fong fong 200000 Node Name =staff [OPEN] Node Value = 揚 木金 mkyong 100000 attr name : id attr value : 1001 Node Name =firstname [OPEN] Node Value =揚 Node Name =firstname [CLOSE] Node Name =lastname [OPEN] Node Value =木金 Node Name =lastname [CLOSE] Node Name =nickname [OPEN] Node Value =mkyong Node Name =nickname [CLOSE] Node Name =salary [OPEN] Node Value =100000 attr name : currency attr value : USD Node Name =salary [CLOSE] Node Name =staff [CLOSE] Node Name =staff [OPEN] Node Value = low yin fong fong fong 200000 attr name : id attr value : 2001 Node Name =firstname [OPEN] Node Value =low Node Name =firstname [CLOSE] Node Name =lastname [OPEN] Node Value =yin fong Node Name =lastname [CLOSE] Node Name =nickname [OPEN] Node Value =fong fong Node Name =nickname [CLOSE] Node Name =salary [OPEN] Node Value =200000 attr name : currency attr value : INR Node Name =salary [CLOSE] Node Name =staff [CLOSE] Node Name =company [CLOSE] 

4. Parse Alexa API XML Response

This example shows how to use the DOM parser to parse the XML response from Alexa’s API.

4.1 Send a request to the following Alexa API.

 https://data.alexa.com/data?cli=10&url=mkyong.com 

4.2 The Alexa API will return the following XML response. The Alexa ranking is inside the POPULARITY element, the TEXT attribute.

4.3 We use a DOM parser to directly select the POPULARITY element and print out the value of the TEXT attribute.

 package com.mkyong.xml.dom; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class ReadXmlAlexaApi < private static final String ALEXA_API = "http://data.alexa.com/data?cli=10&url="; private final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); public static void main(String[] args) < ReadXmlAlexaApi obj = new ReadXmlAlexaApi(); int alexaRanking = obj.getAlexaRanking("mkyong.com"); System.out.println("Ranking: " + alexaRanking); >public int getAlexaRanking(String domain) < int result = 0; String url = ALEXA_API + domain; try < URLConnection conn = new URL(url).openConnection(); try (InputStream is = conn.getInputStream()) < // unknown XML better turn on this dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = dbf.newDocumentBuilder(); Document doc = dBuilder.parse(is); Element element = doc.getDocumentElement(); // find this tag "POPULARITY" NodeList nodeList = element.getElementsByTagName("POPULARITY"); if (nodeList.getLength() >0) < Element elementAttribute = (Element) nodeList.item(0); String ranking = elementAttribute.getAttribute("TEXT"); if (!"".equals(ranking)) < result = Integer.parseInt(ranking); >> > > catch (Exception e) < e.printStackTrace(); throw new IllegalArgumentException("Invalid request for domain : " + domain); >return result; > > 

The domain mkyong.com ranked 20162 .

Note
More DOM parser examples – Oracle – Reading XML Data into a DOM

Источник

Оцените статью