Java Api to Read Xml File From a Url
An XML file contains data betwixt the tags so information technology is complex to read the information when compared to other file formats similar docx and txt. At that place are two types of parsers which parse an XML file:
- Object-Based (due east.g. D.O.M)
- Issue-Based (e.g. SAX, StAX)
In this article, we will discuss how to parse XML using Java DOM parser and Java SAX parser.
Java DOM Parser: DOM stands for Document Object Model. The DOM API provides the classes to read and write an XML file. DOM reads an entire document. It is useful when reading small to medium size XML files. It is a tree-based parser and a footling slow when compared to SAX and occupies more space when loaded into memory. We can insert and delete nodes using the DOM API.
We take to follow the below process to excerpt information from an XML file in Coffee.
- Instantiate XML file:
- Get root node: Nosotros can use getDocumentElement() to get the root node and the chemical element of the XML file.
- Get all nodes: On using getElementByTagName() Returns a NodeList of all the Elements in certificate gild with a given tag name and are independent in the document.
- Get Node by text value: We tin use getElementByTextValue() method in gild to search for a node past its value.
- Get Node by aspect value: we can utilize the getElementByTagName() method along with getAttribute() method.
Let's now see an example on extracting data from XML using Java DOM Parser.
Create a .xml file, in this case, we have created Gfg.xml
XML
<? xml version = "1.0" ?>
< class >
< geek >
< id >i</ id >
< username >geek1</ username >
< EnrolledCourse >D.S.A</ EnrolledCourse >
< style >online self paced</ mode >
< elapsing >Lifetime</ elapsing >
</ geek >
< geek >
< id >2</ id >
< username >geek2</ username >
< EnrolledCourse >Organisation Design</ EnrolledCourse >
< mode >online live grade</ mode >
< duration >10 Lectures</ duration >
</ geek >
< geek >
< id >3</ id >
< username >geek3</ username >
< EnrolledCourse >Competitive Programming</ EnrolledCourse >
< mode >online live form</ mode >
< duration >viii weeks</ duration >
</ geek >
< geek >
< id >4</ id >
< username >geek4</ username >
< EnrolledCourse >Complete Interview Preparation</ EnrolledCourse >
< mode >online cocky paced</ mode >
< elapsing >Lifetime</ elapsing >
</ geek >
</ form >
Now create a coffee file for Java DOM parser. In this case GfgXmlExtractor.java
Java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Certificate;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import coffee.io.File;
public grade GfgXmlExtractor {
public static void main(String argv[])
{
endeavour {
File file = new File(
"F:\\geeksforgeeks_contributions\\gfg.xml" );
DocumentBuilderFactory dbf
= DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Certificate medico = db.parse(file);
dr..getDocumentElement().normalize();
System.out.println(
"Root element: "
+ doc.getDocumentElement().getNodeName());
NodeList nodeList
= physician.getElementsByTagName( "geek" );
for ( int i = 0 ; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
System.out.println( "\nNode Proper name :"
+ node.getNodeName());
if (node.getNodeType()
== Node.ELEMENT_NODE) {
Element tElement = (Element)node;
Organization.out.println(
"User id: "
+ tElement
.getElementsByTagName( "id" )
.item( 0 )
.getTextContent());
System.out.println(
"User Name: "
+ tElement
.getElementsByTagName(
"username" )
.item( 0 )
.getTextContent());
Organization.out.println(
"Enrolled Course: "
+ tElement
.getElementsByTagName(
"EnrolledCourse" )
.item( 0 )
.getTextContent());
Organisation.out.println(
"Way: "
+ tElement
.getElementsByTagName( "mode" )
.item( 0 )
.getTextContent());
System.out.println(
"Duration: "
+ tElement
.getElementsByTagName(
"elapsing" )
.item( 0 )
.getTextContent());
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output
Root element: class Node Name :geek User id: ane User Name: geek1 Enrolled Grade: D.S.A Style: online self paced Duration: Lifetime Node Name :geek User id: 2 User Proper name: geek2 Enrolled Course: System Design Mode: online live course Elapsing: ten Lectures Node Name :geek User id: 3 User Name: geek3 Enrolled Course: Competitive Programming Fashion: online live grade Duration: eight weeks Node Name :geek User id: 4 User Name: geek4 Enrolled Form: Complete Interview Grooming Mode: online self paced Duration: Lifetime
Method ii: Java SAX Parser
SAX Parser in coffee provides API to parse XML documents. SAX parser is a lot more different from DOM parser considering it doesn't load complete XML into retention and read XML certificate sequentially. In SAX, parsing is done by the ContentHandler interface and this interface is implemented by DefaultHandler form.
Let's now see an example on extracting data from XML using Java SAX Parser.
Create a java file for SAX parser. In this case, we take created GfgSaxXmlExtractor.coffee
Java
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 GfgSaxXmlParser {
public static void main(Cord args[])
{
try {
SAXParserFactory factory
= SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean id = simulated ;
boolean username = fake ;
boolean EnrolledCourse = false ;
boolean fashion = false ;
boolean duration = fake ;
public void startElement(
String uri, String localName,
String qName, Attributes attributes)
throws SAXException
{
if (qName.equalsIgnoreCase( "Id" )) {
id = true ;
}
if (qName.equalsIgnoreCase(
"username" )) {
username = true ;
}
if (qName.equalsIgnoreCase(
"EnrolledCourse" )) {
EnrolledCourse = true ;
}
if (qName.equalsIgnoreCase( "mode" )) {
mode = truthful ;
}
if (qName.equalsIgnoreCase(
"duration" )) {
elapsing = true ;
}
}
public void characters( char ch[], int kickoff,
int length)
throws SAXException
{
if (id) {
System.out.println(
"ID : "
+ new String(ch, start,
length));
id = simulated ;
}
if (username) {
Organisation.out.println(
"User Name: "
+ new String(ch, first,
length));
username = false ;
}
if (EnrolledCourse) {
Organization.out.println(
"Enrolled Course: "
+ new Cord(ch, start,
length));
EnrolledCourse = false ;
}
if (manner) {
System.out.println(
"mode: "
+ new String(ch, start,
length));
fashion = faux ;
}
if (duration) {
System.out.println(
"duration : "
+ new Cord(ch, start,
length));
elapsing = false ;
}
}
};
saxParser.parse(
"F:\\geeksforgeeks_contributions\\gfg.xml" ,
handler);
}
take hold of (Exception due east) {
System.out.println(e);
}
}
}
Output
ID : 1 User Proper noun: geek1 Enrolled Course: D.South.A mode: online cocky paced duration : Lifetime ID : 2 User Name: geek2 Enrolled Course: Organisation Blueprint fashion: online live course duration : 10 Lectures ID : 3 User Name: geek3 Enrolled Form: Competitive Programming mode: online live course duration : 8 weeks ID : 4 User Proper name: geek4 Enrolled Course: Consummate Interview Preparation way: online self paced duration : Lifetime
Source: https://www.geeksforgeeks.org/java-program-to-extract-content-from-a-xml-document/
0 Response to "Java Api to Read Xml File From a Url"
Enregistrer un commentaire