Disclosure: This text might include affiliate hyperlinks. While you buy, we might earn a fee.
Easy methods to learn XML file utilizing JDOM in Java
Right here is our pattern XML file:
<?xml model=“1.0” encoding=“UTF-8”?>
<books>
<e book ISBN=“1234”>
<creator>James</creator>
<title>Few phrases</title>
<pages>120</pages>
<language>English</language>
</e book>
<e book ISBN=“5678”>
<creator>Peter</creator>
<title>Across the World</title>
<pages>200</pages>
<language>English</language>
</e book>
</books>
and here’s a Java program which reads this XML doc utilizing JDOM library :
import java.io.IOException;
import java.util.Iterator;
import java.util.Checklist;
import org.jdom2.Doc;
import org.jdom2.Factor;
import org.jdom2.JDOMException;
import org.jdom2.enter.SAXBuilder;
/**
* Java program to learn XML file utilizing JDOM library.
* JDOM is an open supply library which is near Java fashion
* and permits programmer to learn and write XML information in JAva
*
* @creator
*/
public class XMLReader {
public static void primary(String args[]){
//creating JDOM SAX parser
SAXBuilder builder = new SAXBuilder();
//studying XML doc
Doc xml = null;
strive {
xml = builder.construct(new File(“check.xml”));
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//getting root factor from XML doc
Factor root = xml.getRootElement();
System.out.println(“Root factor of XML doc is : “ + root.getName());
System.out.println(“Variety of books on this XML : “ + root.getChildren().dimension());
Checklist<Factor> books = root.getChildren();
//Iterating over all childs in XML
Iterator<Factor> itr = books.iterator();
whereas(itr.hasNext()){
Factor e book = itr.subsequent();
//studying attribute from Factor utilizing JDOM
System.out.println(“ISBN : “ + e book.getAttributeValue(“ISBN”));
//studying worth of childern in XML utilizing JDOM
System.out.println(“creator : “ + e book.getChildText(“creator”));
System.out.println(“title : “ + e book.getChildText(“title”));
System.out.println(“pages : “ + e book.getChildText(“pages”));
System.out.println(“language : “ + e book.getChildText(“language”));
}
}
}
Output:
Root factor of XML doc is : books
Quantity of books in this XML : 2
ISBN : 1234
creator : James
title : Few phrases
pages : 120
language : English
ISBN : 5678
creator : Peter
title : Across the World
pages : 200
language : English
When you have a look at this instance of parsing XML doc utilizing JDOM parser, you will see it surprisingly easy. you simply must create SAXBuilder and you then bought Doc object, from you could get Factor and correspondingly worth of kid and attributes.
That is all on Easy methods to learn XML file utilizing JDOM open supply library. JDOM may be very simple to make use of library for Java programmer and nice for rapidly studying XML paperwork in Java.
Different Java Tutorials chances are you’ll like