In this article, i am going to use the Swing for the UI purpose and for the XML validation against its schema i will use DOM parser as well as SAX Parser. previously we have already seen that how these parsers works in detail.
Application output will look like below snap:

How to validate using DOM Parser :
- Create instance of “DocumentBuilderFactory“.
- Set validation true.
- Set two attributes for schema language and schema source in factory instance.
- Create instance of “DocumentBuilder” from factory and parse.
- Check validateUsingDOM() method in below code.
How to validate using SAX Parser:
- Create instance of “SAXParserFactory“.
- Set validation true.
- Create instance of “SAXParser” from factory object.
- Set two property for schema language and schema source in parser instance and parse.
- Check validateUsingSAX() method in below code.
Complete code:
package com.g2.XML;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class DOMXMLSchemaValidator {
private JFrame frame;
private JTextField txtXSDName;
private final Action action = new SwingAction();
private JFileChooser fc = new JFileChooser();
JTextArea txtResult = new JTextArea();
private JTextField txtXMLName;
private JButton btnValidateUsingDom;
private JButton btnValidateUsingSax;
private JButton btnDisplayActualError;
private String errorMsg;
private JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DOMXMLSchemaValidator window = new DOMXMLSchemaValidator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DOMXMLSchemaValidator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
ApplicationActions btnActions = this.new ApplicationActions();
frame = new JFrame("XML Schema Validator using DOM Parser");
frame.getContentPane().setBackground( Color.LIGHT_GRAY);
frame.setBounds(100, 100, 492, 300);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnSelectXsdFile = new JButton("Select XSD File");
btnSelectXsdFile.setAction(action);
btnSelectXsdFile.setBounds(327, 11, 127, 23);
frame.getContentPane().add(btnSelectXsdFile);
txtXSDName = new JTextField();
txtXSDName.setBounds(10, 12, 298, 23);
frame.getContentPane().add(txtXSDName);
txtXSDName.setColumns(10);
txtXMLName = new JTextField();
txtXMLName.setColumns(10);
txtXMLName.setBounds(10, 46, 298, 23);
frame.getContentPane().add(txtXMLName);
JButton btnSelectXmlFile = new JButton("Select XML File");
btnSelectXmlFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
txtResult.setBackground(Color.ORANGE);
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
txtXMLName.setText(file.getPath());
}
}
});
btnSelectXmlFile.setBounds(327, 45, 127, 23);
btnSelectXmlFile.addActionListener(btnActions);
frame.getContentPane().add(btnSelectXmlFile);
btnValidateUsingDom = new JButton("Validate Using DOM");
btnValidateUsingDom.setBounds(50, 93, 172, 23);
btnValidateUsingDom.addActionListener(new ApplicationActions());
frame.getContentPane().add(btnValidateUsingDom);
btnValidateUsingSax = new JButton("Validate Using SAX");
btnValidateUsingSax.setBounds(262, 93, 164, 23);
frame.getContentPane().add(btnValidateUsingSax);
btnValidateUsingSax.addActionListener(new ApplicationActions());
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 161, 464, 112);
frame.getContentPane().add(scrollPane);
scrollPane.setViewportView(txtResult);
txtResult.setFont(new Font("Monospaced", Font.PLAIN, 13));
txtResult.setBackground(Color.ORANGE);
btnDisplayActualError = new JButton("Display Actual Error");
btnDisplayActualError.setBounds(148, 127, 154, 23);
frame.getContentPane().add(btnDisplayActualError);
btnDisplayActualError.setVisible(false);
btnDisplayActualError.addActionListener(new ApplicationActions());
}
private void validateUsingDOM() {
errorMsg = "";
DocumentBuilderFactory DF = DocumentBuilderFactory.newInstance();
DF.setValidating(true);
DF.setAttribute(
"http://java.sun.com/xml/jaxp/ properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
DF.setAttribute("http://java.sun.com/xml/jaxp/ properties/schemaSource",
txtXSDName.getText());
try {
DocumentBuilder DB = DF.newDocumentBuilder();
DB.parse(txtXMLName.getText());
styleTextBox(false, null);
} catch (ParserConfigurationException e) {
styleTextBox(true, e);
} catch (SAXException e) {
styleTextBox(true, e);
} catch (IOException e) {
styleTextBox(true, e);
} catch (Exception e) {
styleTextBox(true, e);
}
}
private void styleTextBox(boolean isError, Throwable t) {
if (isError) {
btnDisplayActualError.setVisible(true);
txtResult.setBackground(Color.RED);
txtResult
.setText("Document is not validated or Some error occured");
if (t != null) {
getStackTrace(t);
}
} else {
txtResult.setBackground(Color.GREEN);
txtResult.setText("Validation Success...");
}
}
public void getStackTrace(Throwable aThrowable) {
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
errorMsg = result.toString();
}
private void validateUsingSAX() {
SAXParserFactory SF = SAXParserFactory.newInstance();
SF.setValidating(true);
SAXParser SP;
try {
SP = SF.newSAXParser();
SP.setProperty(
"http://java.sun.com/xml/jaxp/ properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
SP.setProperty(
"http://java.sun.com/xml/jaxp/ properties/schemaSource",
txtXSDName.getText());
SP.parse(new File(txtXMLName.getText()), new DefaultHandler());
styleTextBox(false, null);
} catch (ParserConfigurationException e) {
styleTextBox(true, e);
} catch (SAXException e) {
styleTextBox(true, e);
} catch (IOException e) {
styleTextBox(true, e);
} catch (Exception e) {
styleTextBox(true, e);
}
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Select XSD File");
putValue(SHORT_DESCRIPTION, "Select XML schema file present on local disc");
}
public void actionPerformed(ActionEvent e) {
txtResult.setBackground(Color.ORANGE);
if (e.getActionCommand().equals("Select XSD File")) {
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
txtXSDName.setText(file.getPath());
}
}
}
}
private class ApplicationActions implements ActionListener {
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommand().equals("Validate Using DOM")) {
if (validateControls()) {
validateUsingDOM();
}
} else if (evt.getActionCommand().equals("Display Actual Error")) {
txtResult.setText(errorMsg);
} else if (evt.getActionCommand().equals("Validate Using SAX")) {
if (validateControls())
validateUsingSAX();
}
}
private boolean validateControls() {
boolean retVal = true;
if (txtXMLName.getText().trim().equals("")) {
txtXMLName.setBackground(Color.RED);
txtXMLName.setText("Required field");
retVal = false;
}
if (txtXSDName.getText().trim().equals("")) {
txtXSDName.setBackground(Color.RED);
txtXSDName.setText("Required field");
retVal = false;
}
return retVal;
}
}
}
Output:
1. Validation succeeded

2. Validation failed

Sample XSD (Schema) document:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="cricket" type="CricketType" />
<xsd:complexType name="CricketType">
<xsd:sequence>
<xsd:element name="team" type="TeamType" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="TeamType">
<xsd:sequence>
<xsd:element name="player" type="PlayerType" maxOccurs="16" minOccurs="1" />
</xsd:sequence>
<xsd:attribute name="country" type="xsd:string" use="required" />
</xsd:complexType>
<xsd:complexType name="PlayerType">
<xsd:sequence>
<xsd:element name="player-name" type="xsd:string" />
<xsd:element name="total-runs" type="xsd:positiveInteger" />
<xsd:element name="no-of-100s" type="xsd:positiveInteger" />
<xsd:element name="no-of-50s" type="xsd:positiveInteger" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
Sample XML document:
<?xml version="1.0" encoding="utf-8"?>
<cricket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<team country="India">
<player>
<player-name>Player1</player-name>
<total-runs>10000</total-runs>
<no-of-100s>30</no-of-100s>
<no-of-50s>70</no-of-50s>
</player>
<player>
<player-name>Player2</player-name>
<total-runs>1000</total-runs>
<no-of-100s>1</no-of-100s>
<no-of-50s>3</no-of-50s>
</player>
<player>
<player-name>Player3</player-name>
<total-runs>6443</total-runs>
<no-of-100s>12</no-of-100s>
<no-of-50s>23</no-of-50s>
</player>
</Team>
<team country="Australia">
<player>
<player-name>Aussie Player1</player-name>
<total-runs>10000</total-runs>
<no-of-100s>30</no-of-100s>
<no-of-50s>70</no-of-50s>
</player>
<player>
<player-name>Aussie Player2</player-name>
<total-runs>1000</total-runs>
<no-of-100s>1</no-of-100s>
<no-of-50s>3</no-of-50s>
</player>
<player>
<player-name>Aussie Player3</player-name>
<total-runs>6443</total-runs>
<no-of-100s>12</no-of-100s>
<no-of-50s>23</no-of-50s>
</player>
</team>
</cricket>
Leave a Reply