XML File
Create new package named data. In this package, create new xml file named products.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<id>p01</id>
<name>name 1</name>
<price currency="usd">20</price>
<quantity>5</quantity>
<weight unit="kg">2.1</weight>
<date format="dd/MM/yyyy">02/03/2017</date>
<status>true</status>
</product>
<product>
<id>p02</id>
<name>name 2</name>
<price currency="eur">12</price>
<quantity>3</quantity>
<weight unit="kg">6.5</weight>
<date format="dd/MM/yyyy">24/11/2018</date>
<status>true</status>
</product>
<product>
<id>p03</id>
<name>name 3</name>
<price currency="aud">13</price>
<quantity>1</quantity>
<weight unit="kg">7.8</weight>
<date format="dd/MM/yyyy">14/10/2018</date>
<status>false</status>
</product>
</products>
Create ProductModel Class
In models package, create new java class named ProductModel.java contains methods to interact with the xml file.
package models;
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 ProductModel {
private boolean result = false;
public boolean checkId(String id) {
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
saxParser.parse("src\\data\\products.xml", new ProductDefaultHandler(id));
} catch (Exception e) {
this.result = false;
}
return this.result;
}
private class ProductDefaultHandler extends DefaultHandler {
private String tagName = "";
private String id;
public ProductDefaultHandler(String id) {
this.id = id;
}
@Override
public void startDocument() throws SAXException {
result = false;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
this.tagName = qName;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String content = new String(ch, start, length);
if (this.tagName.equalsIgnoreCase("id")) {
if (content.equalsIgnoreCase(this.id)) {
result = true;
}
this.tagName = "";
}
}
}
}
Structure of Project
Run Application
package demo;
import models.ProductModel;
public class Main {
public static void main(String[] args) {
ProductModel productModel = new ProductModel();
System.out.println("Result 1: " + productModel.checkId("p01"));
System.out.println("Result 2: " + productModel.checkId("p04"));
}
}
Output
Result 1: true
Result 2: false