4/17/19

XML Parsing (Reader) in java part -1


XML - eXtensible Markup Language

XML describes the data. It is very light weight and easy to curray the datas.

XML is a user define tags. Unlike HTML Tags (Pre define tags)

XML has one root tag which has several nested tags.

XML Parsing Libraries in java
- DOM (It has with JSD)
- SAX (It has with JSD)
- JDOM (We are using JDOM)
- JAXB
- etc.

DOM , SAX is very old but it has with jdk libraries.

DOM,SAX have a lot of disadvantages.

JDOM, JAXB have not with JDK, we have  to the download the library.
 JDOM Dowload Here 

XML Parsing can read file from .xml file, write the file to .xml file.

 Download the xml file of this project 


XML parsing (Reader) Java code..

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

public class XMLReader {

	public static void main(String[] args) {
		
		//creating JDOM SAX Parser
		SAXBuilder builder =new SAXBuilder();
		
		//reading XML document
		Document xml = null;
		try {
			xml=builder.build(new InputSource("sample.xml"));
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//getting root element from XML Document
		Element root = xml.getRootElement();
		
		System.out.println("Root element of XML Document is : "+root.getName());
		System.out.println("Number of books in this XML : "
+root.getChildren().size());
		
		System.out.println();

		
		List books = root.getChildren();
		
		// Iterating over all childs in XML
		Iterator irt = books.iterator();
		
		while(irt.hasNext()){
			
			Element book = (Element) irt.next();
			
			//reading attributes from Element using JDOM
			System.out.println("ISBN : "+book.getAttributeValue("ISBN"));
			
			//reading value of children in XML using JDOM
			System.out.println("Author : "+book.getChildText("author"));
			System.out.println("Title : "+book.getChildText("title"));
			System.out.println("Pages : "+book.getChildText("pages"));
			System.out.println("Language : "+book.getChildText("language"));
			
			System.out.println();
			
			
		}
		
		System.out.println();
		
	}

}

No comments:

Post a Comment

About

Hi, I'm Najathi.
I've started entrepreneurial company, Twin Brothers.Inc.
One is self-funded & the other is venture backed. I also send a weekly. where I share relevent, curated links.

Every Week I Publish a short post on writing, publishing, or content of IT Related

Contact Form

Name

Email *

Message *