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>

Posted

in

by

Tags:


Related Posts

Comments

4 responses to “Validate XML Schema Using DOM Parser and SAX Parser in JAVA Using Swing”

  1. Aarya Avatar
    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

    1. JitendraZaa Avatar
      JitendraZaa

      What error you are getting?

      1. Aarya Avatar
        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…

        1. saidi Amel Avatar
          saidi Amel

          hi
          i have the same error

          org.xml.sax.SAXNotRecognizedException: La propriété ‘http://java.sun.com/xml/jaxp/ properties/schemaLanguage’ n’est pas reconnue.
          at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.getProperty(AbstractSAXParser.java:2064)
          at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.setProperty(SAXParserImpl.java:575)
          at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.setProperty(SAXParserImpl.java:304)
          at com.mycompany.validatorxml.DOMXMLSchemaValidator.validateUsingSAX(DOMXMLSchemaValidator.java:206)
          at com.mycompany.validatorxml.DOMXMLSchemaValidator.access$700(DOMXMLSchemaValidator.java:41)
          at com.mycompany.validatorxml.DOMXMLSchemaValidator$ApplicationActions.actionPerformed(DOMXMLSchemaValidator.java:255)
          at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
          at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
          at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
          at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
          at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
          at java.awt.Component.processMouseEvent(Component.java:6539)
          at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
          at java.awt.Component.processEvent(Component.java:6304)
          at java.awt.Container.processEvent(Container.java:2239)
          at java.awt.Component.dispatchEventImpl(Component.java:4889)
          at java.awt.Container.dispatchEventImpl(Container.java:2297)
          at java.awt.Component.dispatchEvent(Component.java:4711)
          at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
          at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
          at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
          at java.awt.Container.dispatchEventImpl(Container.java:2283)
          at java.awt.Window.dispatchEventImpl(Window.java:2746)
          at java.awt.Component.dispatchEvent(Component.java:4711)
          at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
          at java.awt.EventQueue.access$500(EventQueue.java:97)
          at java.awt.EventQueue$3.run(EventQueue.java:709)
          at java.awt.EventQueue$3.run(EventQueue.java:703)
          at java.security.AccessController.doPrivileged(Native Method)
          at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
          at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
          at java.awt.EventQueue$4.run(EventQueue.java:733)
          at java.awt.EventQueue$4.run(EventQueue.java:731)
          at java.security.AccessController.doPrivileged(Native Method)
          at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
          at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
          at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
          at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
          at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
          at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
          at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
          at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

          HELP plz

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading