Java XML - SPLessons

Java XML Validations

Home > Lesson > Chapter 3
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java XML Validations

Java XML Validations

shape Description

Generally, Data validation is a checking technique that a PC completes naturally to decrease input errors in information. A typical sort of data validation is the spell-checker work, which is utilized to check for spelling and punctuation mistakes when writing in a word processing record. A well-formed XML archive can be approved against DTD or Schema. A well-formed XML report is an XML archive with right sentence structure and is exceptionally important to think about valid XML archive before knowing XML validation.

DTD And Schema

shape Description

DTD stands for Document Type Definition. It characterizes the lawful building pieces of a XML report. It is utilized to characterize report structure with a rundown of legitimate components and properties. XML schema is a dialect which is utilized for communicating requirement about XML records. There are such a large number of diagram dialects which are utilized now a days for instance XSD (XML schema definition).Following is an example for the schema file. student.xsd [xml] <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.splesson.com" xmlns="http://www.splesson.com" elementFormDefault="qualified"> <xs:element name="student"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:element name="email" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> [/xml]

shape Example

The following is an example to validate students.xml against the students.xsd. students.xml [xml]<?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class>[/xml] students.xsd [xml]<?xml version = "1.0"?> <xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"> <xs:element name = 'class'> <xs:complexType> <xs:sequence> <xs:element name = 'student' type = 'StudentType' minOccurs = '0' maxOccurs = 'unbounded' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name = "StudentType"> <xs:sequence> <xs:element name = "firstname" type = "xs:string"/> <xs:element name = "lastname" type = "xs:string"/> <xs:element name = "nickname" type = "xs:string"/> <xs:element name = "marks" type = "xs:positiveInteger"/> </xs:sequence> <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> </xs:complexType> </xs:schema>[/xml] XSDValidator.java [xml]import java.io.File; import java.io.IOException; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.xml.sax.SAXException; public class XSDValidator { public static void main(String[] args) { if(args.length !=2){ System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" ); } else { boolean isValid = validateXMLSchema(args[0],args[1]); if(isValid){ System.out.println(args[1] + " is valid against " + args[0]); } else { System.out.println(args[1] + " is not valid against " + args[0]); } } } public static boolean validateXMLSchema(String xsdPath, String xmlPath){ try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File(xsdPath)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new File(xmlPath))); } catch (IOException e){ System.out.println("Exception: "+e.getMessage()); return false; }catch(SAXException e1){ System.out.println("SAX Exception: "+e1.getMessage()); return false; } return true; } }[/xml] Output: When compile the code result will be as follows. [xml]students.xml is valid against students.xsd[/xml]

Web.XML file In Java Servlet

shape Introduction

The Servlet Request is an interface which defines different methods to handle the client requests to access a servlet, ServletRequest provides an instance to give the requests of client for the servlet, where servlet container establish a object and send an argument to the service method. Following is the structure of this interface. [java]public interface ServletRequest[/java]

shape Methods

Servlet Request, Following are the methods of the ServletRequest interface.
Methods Description
getParameter(String name) It gives back the estimation of parameter of client ask for sort on the content record and the arrival sort is String.
getParameterValues(String name) It gives back a variety of string which contains all parameter names. It is essentially utilized for the drop down box and it returns String.
getParameterNames() It returns an enumeration.
getContentLength() It returns size of data content and return type is int.
getServerPort() It returns port number and the return type is int.
getServerName() It returns host name of server and the return type is string.
getCharacterEncoding() It returns the set encoding request otherwise it shows null and return type is String.
getCharacterQueryString() It returns the request URL path and the return type is String.
getInputStream() It gets the information stream of the subprocess. The stream gets information from the standard output stream and the return type is ServletInputStream.

shape Conceptual Figure

Servlet Request, Following is the figure to understand that how servlet can manage multiple requests. As discussed that servlet will provide Threads to process the multiple request and this is the advantage of servlet and it overcomes the problem of CGI(Common Gateway Interface).

Example on ServletRequest to display user name

shape Examples

welcome.html [html] <html> <body> <form action="./welcome"> user::<input type="text" name="user"/> fullname::<input type="text" name="fullname"/> <input type="submit" value="go"/> </form> </body> </html> [/html] Here the developer just created two text boxes, one for User and another for full name and also created a submit button that is go. web.xml [xml] <web-app> <servlet> <servlet-name>Demo</servlet-name> <servlet-class>ServletRequest</servlet-class> </servlet> <servlet-mapping> <servlet-name>Demo</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app> [/xml] Here make sure that servlet name should be same and URL pattern should be match with HTML form action URL. ServletRequest.java [java] import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletRequest extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print(""); String username = request.getParameter("user"); ServletConfig config = getServletConfig(); String fullname = request.getParameter("fullname"); out.print(" <h1><b>Hi "+username+" welcome to Splessons</b></h1> "); out.print(" <h2><b>This is your fullname "+fullname+" </b></h2> "); out.print(""); out.flush(); out.close();} } [/java] Where ServletRequest is the class name, this class is broadening HttpServlet, In doGet Method the parameters are affixed to the URL and sent alongside header data, DoGet is quicker in the event that we set the reaction content length since a similar association is utilized. Output: Compile the code from HTML page then the following output will be displayed. After entering the data to the above form result will be as follows.

Summary

shape Key Points

  • CSS can be utilized to add style and show data to a XML archive.
  • XML schema is a dialect which is utilized for communicating requirement about XML records.
  • DTD doesn't support namespace where as XSD supports namespace.