Parsing XML using Java

The idea here is to parse the employees.xml file with content as below

<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
  <Employee type="permanent">
        <Name>Seagull</Name>
        <Id>3674</Id>
        <Age>34</Age>
   </Employee>
  <Employee type="contract">
        <Name>Robin</Name>
        <Id>3675</Id>
        <Age>25</Age>
    </Employee>
  <Employee type="permanent">
        <Name>Crow</Name>
        <Id>3676</Id>
        <Age>28</Age>
    </Employee>
</Personnel>

From the parsed content create a list of Employee objects and print it to the console. The output would be something like

Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.
Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.
Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.
 
 
 // Create the Factory and Document builder
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder docBuilder = factory.newDocumentBuilder();

// Parse the xml document as input stream
 Document document = docBuilder.parse(new ByteArrayInputStream(responseStr.getBytes()));
 
// Read the document element or the root of the document
Element docElement = document.getDocumentElement();
//This will read the value of a given code element
String responseCode = getTextValue(docElement, "Name");



private String getTextValue(final Element element, final String tagName)
    {
        NodeList nl = element.getElementsByTagName(tagName);
        if (null != nl && nl.getLength() > 0)
        {
            Element ele = (Element) nl.item(0);
            return ele.getFirstChild().getNodeValue();
        }
        return null;
    } 

 

Comments

Harrah's Resort Southern California - Mapyro
Harrah's 광주 출장안마 Resort Southern California, profile 통영 출장안마 picture. Valley Center, CA 92082, USA. Directions · (760) 943-5000. Find 구미 출장샵 address. 상주 출장마사지 777 Harrah's Rincon 남원 출장안마 Way

Popular posts from this blog

PostgreSQL bytea and oid

MySQL as Hive metadata store

Microservices Architecture with Spring Boot in 15mins