XML Validation

XML is stand for EXtensible Markup Language and it is easy to use XML as a markup language.XML haven't got any predefined tags as HTML.Therefor when we are using a XML content, we have to use a mechanism to read those tags and identify those tags separately.

For this mechanism there are XML parsers.Specially we can use SAX parser and DOM parser.In most web browsers they have an inbuilt XML parser.

DOM parser is effective than the SAX parser. SAX uses an event callback mechanism requiring you to code methods to handle events thrown by the parser as it encounters different entities within the XML document.

DOM parses an XML document and returns an instance of org.w3c.dom.Document. This document object's tree must then be "walked" in order to process the different elements.

JDOM is an open source API, designed specifically for Java programmers, that represents an XML tree as Elements and Attributes. JDOM can interact with SAX or DOM. With JDOM, you construct an instance of a builder.

Lets look at how to validate a XML string using java. I have used the DOM API for that.In this example I have used a XML string to validate



import java.io.IOException;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.InputSource;
/**
*
* @author Dulan Dissanayake
*/
public class XmlValidator {

private boolean isValid = false;

public static void main(String [] args){

//this is the XML string change this and check the validiti of the string
String xmlString = "abc";

validate(xmlString);
System.out.println("Is document valid ?--------"+b);
}



public static boolean validate(String xmlString) {

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);

DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));

return (isValid=true);

} catch (Exception ex) {
System.out.println("Exception"+ex);
return (isValid=false);
}finally{

}


}


}

Comments

Hello there thanks for sharing the information for the XML Validation and its a nice and helpful to the developer and XML is stand for EXtensible Markup Language and it is easy to use XML as a markup language and DOM parses an XML document and returns an instance of org.w3c.dom.Documentand if you wamt to know more information visit site:http://www.hexainfosoft.in

Popular posts from this blog

SSL Pinning in Android

Java Unit testing using JUnit @RunWith(Suite.class)

Android Event Bus Implementations using Otto