Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Wednesday, May 11, 2011

Validating XML Using Standard Java

XML processing is included in standard Java.  This is a function that can be integrated into applications like Talend Open Studio for a quick of an XML string for well-formedness.

The following Java test program uses standard Java XML processing.  These are classes found in the JDK.

To make a Talend routine, be sure to fully-qualify each class name when using the "Create routine" command.  For example, "SAXParser parser" becomes "javax.xml.parsers.SAXParser parser".

package xml;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLValTest {

public static boolean isValidXML(String _s, String _charset) throws Exception {

   boolean result = false;
   try {
    SAXParserFactory factory = SAXParserFactory.newInstance();

    SAXParser parser = factory.newSAXParser();

    InputStream is = new ByteArrayInputStream(_s.getBytes(_charset));

    parser.parse(is, new DefaultHandler());

    result = true;
}
catch(SAXParseException ignore) {}

return result;
}

/**
* @param args
*/
public static void main(String[] args) throws Exception {

   String xml_s = "<message>Hello, World</message>";

   String invalidXML_s = "<message>Hello, World";

   System.out.println("good xml=" + isValidXML(xml_s, "ISO8859_1") );

   System.out.println("bad xml=" + isValidXML(invalidXML_s, "ISO8859_1"));
  }

}

No comments:

Post a Comment