Wednesday, November 5, 2014

How to read the value of a attribute of a XML tag in Java

4:36 PM

How to read the value of a attribute of a XML tag using Java core library. Attributes reside inside the tag and can be read using the org.w3c.dom and javax.xml.Xpath package. There are several others ways also to achieve the same behavior.

For example you have a below XML file .


<?xml version="1.0" encoding="UTF-8"?>
<details name="person-detail" >
    <property name="personal">
        <value text="Mr.XYZ"/>
        <value text="Teacher" />
        <value text="Single" />
    </property>   
</details>


and you want to read the value of text attribute of a value tag of above XML using java and print it on console.

Expected Output:
Mr.XYZ
Teacher
Single


Given below is the code to achieve expected behavior using java.
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.*;
import javax.xml.xpath.*;

public class XMLRead
{

    public static void main(String args[]) 
    {
        try 
        {
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document dDoc = builder.parse("C:\\MyXMLFile.xml");
   XPath xPath = XPathFactory.newInstance().newXPath();
   NodeList nodes1 = (NodeList) xPath.evaluate("/details/property[@name='personal']/value/@text", dDoc, XPathConstants.NODESET);
   for (int j = 0; j < nodes1.getLength(); j++) {
   Node node1 = nodes1.item(j);
   System.out.println(node1.getTextContent()); 
   }

        } 
  catch (Exception e) 
        {
            e.printStackTrace();
        }

    }
}

Above code produces the below output.


0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy