Validate XML Schema Using DOM Parser and SAX Parser in JAVA Using Swing

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 3 Comments on Validate XML Schema Using DOM Parser and SAX Parser in JAVA Using Swing

Validate XML Schema Using DOM Parser and SAX Parser in JAVA Using Swing

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:

Input Screen - XML Schema Validation in JAVA Using DOM and SAX Parser
Input Screen - XML Schema Validation in JAVA Using DOM and SAX Parser

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

Validation Success - XML Schema Validation in JAVA Using DOM and SAX Parser
Validation Success - XML Schema Validation in JAVA Using DOM and SAX Parser

2. Validation failed

Validation Fail - XML Schema Validation in JAVA Using DOM and SAX Parser
Validation Fail - XML Schema Validation in JAVA Using DOM and SAX Parser

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>

Related posts

  • Aarya

    Hi Jitendra.,

    I don no why but the code above is showing me error for these to statements.

    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());”

    PLease provide help on this mater as i am new to JAVA SWING ASAP.

    Regards:
    Mrs. Aarya Deshpande
    umabca55@gmail.com

    • JitendraZaa

      What error you are getting?

      • Aarya

        the error is:

        Exception in thread “AWT-EventQueue-0″ java.lang.

        IllegalArgumentException: Property ‘http://java.sun.com/xml/jaxp/ properties/schemaSource’ is not recognized.

        at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl.setAttribute(Unknown Source)
        at domxmlSchemaValidator.XmlValidator.validateUsingDOM(XmlValidator.java:155)
        at domxmlSchemaValidator.XmlValidator.access$3(XmlValidator.java:146)

        at domxmlSchemaValidator.XmlValidator$ApplicationActions.actionPerformed(XmlValidator.java:250)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)

        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)

        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)

        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)

        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)

        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)

        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)”

        What do i need to do??

        Plz help ASAp…