Saturday, May 23, 2015

Writing XML File Using DOM Parser

Still now we learn how to read XMLfile using DOM, SAX and STAX parser and we know that only DOM and STAX have the ability to write XML file.Here we learn how to write XML file using DOM and later we know how to write XML File using STAX parser.

Step 1:
    Create DocumentBuilderFactory object .
      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

Step 2:

    Create DocumentBuilder object .
      DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

Step 3:
    Create Document object .
      Document dom = domBuilder.newDocument();

Step 4:
    Create Element object .
      Element rootStart = dom.createElement("elementName")

Step 5:
   Add this object to dom .
      dom.appendChild(rootStart);

  If  this node is under any node then add this under any element object  
      rootStart.appendChild(rootStart)

Step 6: 
    Create Attribute Object and set value 
        Attr attribte = dom.createAttribute("attributeName");
        attribte.setValue("attributeValue");

    Add Attribute object with appropriate node
        root.setAttributeNode(attribte);

 

Step 7:
   Create TransformerFactory object
       TransformerFactory transFactory = TransformerFactory.newInstance();

Step 8:
    Create Transformer object.
        Transformer transformer = transFactory.newTransformer();

Step 9:
    Create DOMSource Object .
        DOMSource domSource = new DOMSource(dom);

Step 10:
    Create  StreamResult object and show the file into the console or save in file.

        //Show the file in console
        StreamResult console = new StreamResult(System.out);
        transformer.transform(domSource, console);


         //Save the XML File
        StreamResult xmlFile = new StreamResult(new File("File Path"));
        transformer.transform(domSource, xmlFile);

   
Example Code Given Below :


package domparsing;

import java.io.File;
import java.io.StringWriter;
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.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class DOMWriterExample {

    public static void main(String[] args) throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
        /**
         * Create DocumentBuilderFactory Object.
         */

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        /**
         * Create DocumentBuilder object.
         */

        DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
        /**
         * Create Document object.
         */

        Document dom = domBuilder.newDocument();
        /**
         * Create root element students and add to DOM .
         */

        Element rootStart = dom.createElement("students");
        dom.appendChild(rootStart);

        /**
         * Add student node under students node.
         */

        Element root = dom.createElement("student");
        rootStart.appendChild(root);

        /**
         * Adding Attribute in student node.
         */

        Attr attribte = dom.createAttribute("id");
        attribte.setValue("1");
        root.setAttributeNode(attribte);

        /**
         * Add fname,lname and section under student node and attribute also.
         */

        Element childNodeFirstName = dom.createElement("fname");
        childNodeFirstName.setTextContent("TestFirstName");
        root.appendChild(childNodeFirstName);

        Element childNodeLastName = dom.createElement("lname");
        childNodeLastName.setTextContent("TestLastName");
        root.appendChild(childNodeLastName);

        Element childNodeSectionName = dom.createElement("sectionname");
        childNodeSectionName.setAttribute("rollno", "1");
        childNodeSectionName.setTextContent("A");
        root.appendChild(childNodeSectionName);
        /**
         * Create TransformerFactory and set property.
         */

        TransformerFactory transFactory = TransformerFactory.newInstance();
        //transFactory.setAttribute("indent-number", 4);
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        /**
         * Create DOMSource object and pass DOM object as a parameter.
         */

        DOMSource domSource = new DOMSource(dom);

        /**
         * Showing output on Console.
         */

        StreamResult console = new StreamResult(System.out);
        transformer.transform(domSource, console);
        /*
         StreamResult result = new StreamResult(new StringWriter());
         transformer.transform(domSource, result);
         String xmlString = result.getWriter().toString();
         System.out.println(xmlString);
         */


        /**
         * Storing XML into the file.
         */

        StreamResult xmlFile = new StreamResult(new File("C:\\file.xml"));
        transformer.transform(domSource, xmlFile);
    }
}

 


 

Unknown XML Parsing With STAX

On our last discussion we can now say that we know how to parse a XML file using STAX parser.Now here we try to parse a XML file with unknown structure.It has similar logic which we use in SAX parser to parse a unknown XML.We get the text when Starting Element and End Element name matched.

Code is Given Below For Both Type Of STAX Parser :

Event Or Iterator STAX
----------------------------------------------------------------------------------------------


package STAXParser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;

public class STAXEventParserExample {

    public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
        String startElement = null;
        String endElement = null;
        String elementTxt = null;
        Map<String, String> tmpAtrb = null;
        /**
         * Create XMLInputFactory Factory.
         */

        XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
        /**
         * Create XMLEventReader.
         */

        XMLEventReader xmlEvtReader = xmlFactory.createXMLEventReader(new InputStreamReader(new FileInputStream("c:\\file.xml"), "UTF-8"));
        /**
         * Iterate until last Element in XML.
         */

        while (xmlEvtReader.hasNext()) {
            /**
             * Move To Next XML Element And Check Element Type.
             */

            XMLEvent evnt = xmlEvtReader.nextEvent();
            if (evnt.isStartElement()) {
                tmpAtrb=new HashMap();
                startElement = evnt.asStartElement().getName().getLocalPart();
                for (Iterator<Attribute> iterator = evnt.asStartElement().getAttributes(); iterator.hasNext();) {
                    Attribute attribute = iterator.next();
                    String aname = attribute.getName().getLocalPart();
                    String value = attribute.getValue();
                    tmpAtrb.put(aname, value);
                }
            }
            if (evnt.isEndElement()) {
                endElement = evnt.asEndElement().getName().toString();
                if (startElement.equalsIgnoreCase(endElement)) {
                    System.out.println(" ElementName : " + startElement + " ElementText : " + elementTxt);
                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                        System.out.println(" Attribute Name :" + entrySet.getKey() + " Attribute Value :" + entrySet.getValue());
                    }
                }
            }
            if (evnt.isCharacters()) {
                elementTxt = (evnt.asCharacters().getData().contains("\n")) ? "" : evnt.asCharacters().getData();
            }
        }
        /**
         * Close XMLEventReader
         */

        xmlEvtReader.close();
    }
}
 

Stream Or Cursor STAX
----------------------------------------------------------------------------------------------
package STAXParser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class STAXStreamParserExample {

    public static void main(String[] args) throws FileNotFoundException, XMLStreamException {
        String startElement = null;
        String endElement = null;
        String elementTxt = null;
        Map<String, String> tmpAtrb = null;
        /**
         * Create XMLInputFactory Factory.
         */

        XMLInputFactory xf = XMLInputFactory.newInstance();
        /**
         * Create XMLStreamReader.
         */

        XMLStreamReader xsr = xf.createXMLStreamReader(new InputStreamReader(new FileInputStream("c:\\file.xml")));
        /**
         * Iterate until last Element in XML.
         */

        while (xsr.hasNext()) {
            /**
             * Move To Next XML Element And Check Element Type.
             */

            int e = xsr.next();
            if (e == XMLStreamConstants.START_ELEMENT) {
                startElement = xsr.getLocalName();
                tmpAtrb = new HashMap();
                for (int i = 0; i < xsr.getAttributeCount(); i++) {
                    String aname = xsr.getAttributeLocalName(i);
                    String value = xsr.getAttributeValue(i);
                    tmpAtrb.put(aname, value);
                }
            }

            if (e == XMLStreamConstants.END_ELEMENT) {
                endElement = xsr.getLocalName();
                if (startElement.equalsIgnoreCase(endElement)) {
                    System.out.println(" ElementName : " + startElement + " ElementText : " + elementTxt);
                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                        System.out.println(" Attribute Name :" + entrySet.getKey() + " Attribute Value :" + entrySet.getValue());
                    }
                }
            }
            if (e == XMLStreamConstants.CHARACTERS) {
                elementTxt = (xsr.getText().contains("\n")) ? "" : xsr.getText();
            }
        }
        /**
         * Close XMLEventReader
         */

        xsr.close();
    }
}
 


Sunday, May 17, 2015

Reading XML With STAX Stream Or Cursor API

STAX Stream or Cursor API is a low level pull based API for parsing XML.Its' need less memory than Event or Iterator API because it does not require to create object for each event.

We need to follow this steps to parse a XML file
Step 1:
    Create XMLInputFactory object
         XMLInputFactory xf=XMLInputFactory.newInstance();

Step 2:
     Create XMLStreamReader object  for the input XML.
          XMLStreamReader xsr=xf.createXMLStreamReader(new InputStreamReader(File));

Step 3:
    Iterate the XMLStreamReader object  and identify the various elements in the document
          while (xsr.hasNext()) {
              int e = xsr.next();

          }

Step 4: 
    After reading the entire document , close the XMLStreamReader object.
         xsr.close(); 

Sample Example Code Given Below :


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class STAXStreamParserExample {

    public static void main(String[] args) throws FileNotFoundException, XMLStreamException {
        /**
         * Create XMLInputFactory Factory.
         */

        XMLInputFactory xf = XMLInputFactory.newInstance();
        /**
         * Iterate until last Element in XML.
         */

        XMLStreamReader xsr = xf.createXMLStreamReader(new InputStreamReader(new FileInputStream("c:\\file.xml")));
        /**
         * Iterate until last Element in XML.
         */

        while (xsr.hasNext()) {
            /**
             * Move To Next XML Element And Check Element Type.
             */

            int e = xsr.next();
            if (e == XMLStreamConstants.START_ELEMENT) {
                System.out.println("StartElement Name :" + xsr.getLocalName());
            }
            if (e == XMLStreamConstants.END_ELEMENT) {
                System.out.println("EndElement Name :" + xsr.getLocalName());
            }
            if (e == XMLStreamConstants.CHARACTERS) {
                System.out.println("Element TextValue :" + xsr.getText());
            }
        }
        /**
         * Close XMLEventReader
         */

        xsr.close();
    }
}

 

Reading XML With STAX Event Or Iterator API

STAX Parser is modern parser which is act as pull based parser, means application have control over this parser how and when read the next tag on xml file. It have another advantage that using this parser we can also write a xml file.

STAX is event base xml parser API so it will not load the whole xml file into the memory so we can safe from memory out of bound exception.

STAX API have 2 type.

 1. Event Or Iterator base
 2. Stream Or Cursor base

We will learn here STAX Event or Iterator base API.

Step 1:
  Create and XMLInputFactory instance.
      
        XMLInputFactory xmlFactory=XMLInputFactory.newInstance();

Step 2:
  Create XMLEventReader instance with FileInputStream of input file as argument.
        XMLEventReader xmlEvtReader=xmlFactory.createXMLEventReader("File");
Step 3:
  Iterate the XMLEventReader object  and identify the various elements in the document
       while (xmlEvtReader.hasNext()) {
            XMLEvent evnt = xmlEvtReader.nextEvent();

        }

Step 4:
  After reading the entire document , close the XMLEventReader object.
       xmlEvtReader.close();

Sample Example Code Given Below :


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;


public class STAXEventParserExample {

    public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException {
        /**
         * Create XMLInputFactory Factory.
         */

        XMLInputFactory xmlFactory=XMLInputFactory.newInstance();
        /**
         * Create XMLEventReader.
         */

        XMLEventReader xmlEvtReader=xmlFactory.createXMLEventReader(new InputStreamReader(new FileInputStream("c:\\file.xml"), "UTF-8"));
        /**
         * Iterate until last Element in XML.
         */

        while (xmlEvtReader.hasNext()) {
            /**
             * Move To Next XML Element And Check Element Type.
             */

            XMLEvent evnt = xmlEvtReader.nextEvent();
            if(evnt.isStartElement()){
                System.out.println(evnt.asStartElement().getName());
            }
            if(evnt.isEndElement()){
                System.out.println(evnt.asEndElement().getName());
            }
            if(evnt.isCharacters()){
                System.out.println(evnt.asCharacters().getData());
            }
        }
        /**
         * Close XMLEventReader
         */

        xmlEvtReader.close();
    }   
}

Saturday, May 9, 2015

Unknown XML Structure Parsing Using SAX Parser

We learn how to parse a XML file using SAX parser previously but there we know the XML file structure means node structure.

Now we concentrate how to parse a XML file when we not aware of the structure of a XML file using SAX parser.

It can be possible if we do some modification on DefaultHandler part.

Here we parse a xml in such a manner where we find only the child element at last depth means, this node does not contains any child element .We also retrive attributes of this element.
So logic is that if we find that start element name follows the end element name  then we print the value of this node and attribute value.

Example code given below:


package SAXParser;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class SAXParserExample {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {

        /**
         * We can pass the class name of the XML parser
         * to the SAXParserFactory.newInstance().
         */


        //SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);

        SAXParserFactory saxDoc = SAXParserFactory.newInstance();
        SAXParser saxParser = saxDoc.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {
            String tmpElementName = null;
            String tmpElementValue = null;
            Map<String,String> tmpAtrb=null;

            @Override
            public void startElement(String uri, String localName, String qName, 

                                                                Attributes attributes) throws SAXException {
                tmpElementValue = "";
                tmpElementName = qName;
                tmpAtrb=new HashMap();
                //System.out.println("Start Element :" + qName);

                /**
                 * Store attributes in HashMap
                 */

                for (int i=0; i<attributes.getLength(); i++) {
                    String aname = attributes.getLocalName(i);
                    String value = attributes.getValue(i);
                    tmpAtrb.put(aname, value);
                }

            }

            @Override
            public void endElement(String uri, String localName, String qName) 

                                                        throws SAXException {
              
                if(tmpElementName.equals(qName)){
                    System.out.println("Element Name :"+tmpElementName);


                /**
                 * Retrive attributes from HashMap
                 */
                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                        System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
                    }
                    System.out.println("Element Value :"+tmpElementValue);
                }
            }

            @Override
            public void characters(char ch[], int start, int length) throws SAXException {
                tmpElementValue = new String(ch, start, length) ;
              
            }
        };
      
        /**
         * Below two line used if we use SAX 2.0
         * Then last line not needed.
         */

      
        //saxParser.setContentHandler(handler);
        //saxParser.parse(new InputSource("c:/file.xml"));


        saxParser.parse(new File("c:/file.xml"), handler);
    }
}

XML Reading With SAX Parser

On previous post we learn how to reading a XML file using DOM parser.Here we learn how parse a XML file using SAX(Simple API for XML) parser.

SAX parser is push based eventdriven parser means when we read a XML file then event fire for every tag on XML file and push based means when we try to parse a xml file from application then application cannot have control on this parser it will parse all node and push data to application.

In DOM parser we need to load whole XML file into the memory to read this but in SAX we don't need to load whole XML file into the memory, So we will never get memory out of bound exception for very large XML file.

Using SAX Parser we cannot write a XML file.

We need to follow this steps to parse a XML file

Step 1:
   Create SAXParserFactory instance using
                 SAXParserFactory saxDoc = SAXParserFactory.newInstance();
Step 2:
   Create a SAXParser from SAXParserFactory instance
                 SAXParser saxParser = saxDoc.newSAXParser();
Step 3:
   Create handler for parsing a XML where we define what parser do, when find a StartElement(means <Element>),EndElement(means </Elelement>) or a Character between Start and End Element; for an example:
  
  DefaultHandler handler = new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName,String qName, Attributes attributes)
                    throws SAXException {
                System.out.println("Start Element :" + qName);
            }

            @Override
            public void endElement(String uri, String localName,String qName) throws SAXException {
                System.out.println("End Element :" + qName);
            }

            @Override
            public void characters(char ch[], int start, int length) throws SAXException {

                   System.out.println(new String(ch, start, length));
            }
        }; 


Staep 4:
      Now we need to register this handler to parser using this
              saxParser.parse(new File("FilePath"), handler); 
 

Note :
1. If we are try to use SAXParser 2.0 then we use only
       XMLReader saxParser = XMLReaderFactory.createXMLReader();
 to create parser instance. We don't need to go Step1 for creating factory because it call this internally.
2. For SAXParser 2.0 we need to register handler using
        saxParser.setContentHandler(handler);
and then pass the filename using this
        saxParser.parse(new InputSource("c:/test.xml"));
and ignore the Step 4 code.


package SAXParser;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserExample {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {
        /**
         * We can pass the class name of the XML parser
         * to the SAXParserFactory.newInstance().
         */

      
        //SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);
      
        SAXParserFactory saxDoc = SAXParserFactory.newInstance();
        SAXParser saxParser = saxDoc.newSAXParser();
        /**
         * If we use SAX 2.0 then we need this line and
         * SAXParserFactory,SAXParser not needed and we
         * can commented out above two lines.
         */

      
        //XMLReader saxParser = XMLReaderFactory.createXMLReader();

        DefaultHandler handler = new DefaultHandler() {
             boolean fname = false;
             boolean lname = false;
             boolean section = false;
        
            @Override
            public void startElement(String uri, String localName, String qName, 

                                                                       Attributes attributes)  throws SAXException {
                System.out.println("Start Element Element :" + qName);
                if (qName.equalsIgnoreCase("FNAME")) {
                 fname = true;
                 }

                 if (qName.equalsIgnoreCase("LNAME")) {
                 lname = true;
                 }

                 if (qName.equalsIgnoreCase("SECTIONNAME")) {
                 section = true;
                 }    

                for (int i=0; i<attributes.getLength(); i++) {
                      String aname = attributes.getLocalName(i);
                      String value = attributes.getValue(i);
                      System.out.println("Attribute Name : " + aname + " Attribut Value : " + value);       
                 }

            @Override
            public void endElement(String uri, String localName, String qName)

                                                              throws SAXException   
            {
                System.out.println("End Element :" + qName);
            }
          
            @Override
            public void characters(char ch[], int start, int length) throws SAXException {
              
                 if (fname) {
                 System.out.println("First Name : " + new String(ch, start, length));
                 fname = false;
                 }

                 if (lname) {
                 System.out.println("Last Name : " + new String(ch, start, length));
                 lname = false;
                 }
                 if (section) {
                 System.out.println("Section Name : " + new String(ch, start, length));
                 section = false;
                 }        
            }
        };
        /**
         * Below two line used if we use SAX 2.0
         * Then last line not needed.
         */

        //saxParser.setContentHandler(handler);
        //saxParser.parse(new InputSource("c:/file.xml"));

        saxParser.parse(new File("c:/file.xml"), handler);
    }
}


 Sample XML :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<student id="1">
  <fname>TestFirstName</fname>
  <lname>TestLastName</lname>
  <sectionname rollno="1">A</sectionname>
</student>
 




 

Friday, May 1, 2015

XML Reading With DOM Parser

We need to read XML file for Automation,when some testdata is into the xml file.There are many way to read xml file and many API(Application Programming Interface) for this. We will try to learn here

1.DOM (Document Object Model)
2.SAX (Simple API for XML)
3.STAX (STreaming API for XML)
    a. Event or Iterator API
    b. Stream or Cursor API

Here we learn DOM parser later we know how to use SAX and STAX parser.

To reading any XML file using DOM we need to follow this steps:

Step 1:
 Create DocumentBuilderFactory using
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance()

Step 2:
 Create DocumentBuilder object
         DocumentBuilder db = dbf.newDocumentBuilder();

Step 3:
  Create Document from file.
        Document doc = db.parse(new File("filemane"));
Step 4:
    Now Parse the the XML document


package domparsing;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMParsing {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        /**
         * DocumentBuilderFactory.newInstance() return instance of XMLDom parser
         * We can also specify the ClassName directly for XMLParser in newInstance method like

         * DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance
         * ("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl",null)
        */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File("c:/test.xml"));
        doc.normalizeDocument();
        

         /**
         * Getting Particular node details
         */

        getNodeDetails(doc, "source");
        if (doc.hasChildNodes()) {
           

             /**
             * Getting all child node from XMLDocument using
             * doc.getDocumentElement().getChildNodes() Or doc.getChildNodes()
            */

            //getAllNodeNAttribute(doc.getDocumentElement().getChildNodes());
            getAllNodeNAttribute(doc.getChildNodes());
        }
    }

    public static void getAllNodeNAttribute(NodeList nodes) {
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                System.out.println("Node Start: " + node.getNodeName() + " [Start]");
                if (node.hasAttributes()) {
                    // get attributes names and values
                    NamedNodeMap nodeAttrbs = node.getAttributes();
                    for (int j = 0; j < nodeAttrbs.getLength(); j++) {
                        Node attrNode = nodeAttrbs.item(j);
                        System.out.println("attr name: " + attrNode.getNodeName());
                        System.out.println("attr value: " + attrNode.getNodeValue());
                    }
                }
                if (node.hasChildNodes()) {
                    getAllNodeNAttribute(node.getChildNodes());
                    System.out.println("Node Close: " + node.getNodeName() + " [CLOSE]");
                }
                if (!node.hasChildNodes()) {
                    System.out.println("Node Close: " + node.getNodeName() + " [CLOSE]");
                }
            } else if ((nodes.getLength() <= 1)) {
                System.out.println("Node Text: " + node.getNodeValue());
            }
        }
    }

    public static void getNodeDetails(Document doc, String nodeName) {
        NodeList nodes = doc.getElementsByTagName(nodeName);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            System.out.println("Node Name : " + node.getNodeName());
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                System.out.println("Type Attribute : " + element.getAttribute("type"));
                System.out.println("Media Attribute : " + element.getAttribute("media"));
                if (element.getElementsByTagName("special").getLength() > 0) {
                    System.out.println("Special Tag : " + element.getElementsByTagName("special").item(0).getTextContent());
                    System.out.println("Special Tag Attribue : " + element.getElementsByTagName("special").item(0).getAttributes().item(0).getNodeName());
                }
            }
        }
    }
}


Example XML:

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source media="text">
    <special type="xml">Special Text</special>
    </source>
</ep>