This discussion is archived
12 Replies Latest reply: Feb 2, 2012 9:39 AM by tsuji RSS

XML schema Validation issue when validating a correct new Document in memor

914707 Newbie
Currently Being Moderated
So I have found a possible error within the validation or document library

Here is my code to replicate the problem (Yes, I know it is long)
package Classes;


import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReplicationBugValidationWithNewDom {
     //Appends an item to a node in a document given the item as a string and the text to associate to that item.
     private Element append(Document doc, Element element, String item, String text) {
          Element temp = null;
          if(element == null) {return null;}
          temp = doc.createElement(item);
          if(text != null) {
          return temp;
     //Reproduces a bug found in jaxp where a new document is built without a template, but 
     //is unable to validate the file to the schema correctly due to some bug (when the document is valid to the schema).
     //A work around is to avoid using the validator method, convert the document to an inputstream,
     //and "reparse" the document in the builder factory after attaching a schema to the parser.
     //This relies on the AddressSchema.xsd file within the XMLFiles dir.  
     public ReplicationBugValidationWithNewDom() throws IOException, SAXException, TransformerConfigurationException, TransformerFactoryConfigurationError {
          Document doc = null;
          DocumentBuilder db = null;
          final String JAXP_SCHEMA_SOURCE = 
          String filePath = new File(".").getCanonicalPath();
          File schemaFile = new File(filePath + "AddressSchema.xsd");
          Element root = null;
          Element name = null;
          try {                         
               //Build a document parser
               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
               //Set up schema for factory
               dbf.setAttribute(JAXP_SCHEMA_SOURCE, schemaFile);
               db = dbf.newDocumentBuilder();
               doc = db.newDocument();     
          } catch (Exception e) {
          //Add items to doc in order to validate with schema.
          try {
               root = doc.createElement("address");
               //Hardcode - Grab items from list and put into DOM
               name = append(doc, root, "name", null);
               append(doc, name, "title", "Mr." );                 
               append(doc, name, "first-Name", "Billy");   
               append(doc, name, "last-Name", "Madison" );  
               append(doc, root, "street", "111 blah street" ); 
               append(doc, root, "city", "Cashville" );   
               append(doc, root, "state", "VA" );  
               append(doc, root, "postal-code", "99933-2244");  
          } catch (Exception e) {
          // build an XSD-aware SchemaFactory
          SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );

          // hook up ErrorHandler implementation.
          schemaFactory.setErrorHandler(new ErrorHandler() {
               public void error(SAXParseException ex) throws SAXException {  throw ex;}
               public void fatalError(SAXParseException ex) throws SAXException {  throw ex;}
               public void warning(SAXParseException ex)throws SAXException {  throw ex;}

          // get the custom xsd schema describing the required format for my XML files.
          Schema schemaXSD = schemaFactory.newSchema( schemaFile );

          // Create a Validator capable of validating XML files according to my custom schema.
          Validator validator = schemaXSD.newValidator();
          //confirm root "address" exists
          NodeList nl = doc.getElementsByTagName("address");
          Node n = nl.item(0);
          System.out.println("Before validation, Document has " + n.getNodeName().toString());
          //Output entire document object to system out
          Transformer t = TransformerFactory.newInstance().newTransformer();
          t.setOutputProperty(OutputKeys.INDENT, "yes");
          //Convert to string writer
          StreamResult result = new StreamResult(new StringWriter());
          DOMSource source = new DOMSource(doc);
          //Transform to string
          try {
               t.transform(source, result);
          } catch (TransformerException e1) {
               // TODO Auto-generated catch block
          //Copy result to string and print
          String xmlString = result.getWriter().toString();
          //The problem below here fails.
          try {
               validator.validate(new DOMSource (doc));
          } catch (Exception e) {
     public static void main (String args[]) throws IOException, SAXException {
          try {
               ReplicationBugValidationWithNewDom d = new ReplicationBugValidationWithNewDom();                         
          } catch (Exception e) {

The Output:

Before validation, Document has address
<?xml version="1.0" encoding="UTF-8"?><address>
<street>111 blah street</street>
cvc-elt.1: Cannot find the declaration of element 'address'.

In the code, you notice that I add to the document object correctly and after converting the document object to a string, it does print out that it has all the correct tags. However, it can not find the address "root" element.


Here is AddressSchema.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="">
<xsd:element name="address">
<xsd:element ref="name"/>
<xsd:element ref="street"/>
<xsd:element ref="city"/>
<xsd:element ref="state"/>
<xsd:element ref="postal-code"/>

<xsd:element name="name">
<xsd:element ref="title" minOccurs="0" maxOccurs="1"/>
<xsd:element ref="first-Name"/>
<xsd:element ref="last-Name"/>

<xsd:element name="title" type="xsd:string"/>
<xsd:element name="first-Name" type="xsd:string"/>
<xsd:element name="last-Name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>

<xsd:element name="state">
<xsd:restriction base="xsd:string">
<xsd:length value="2"/>

<xsd:element name="postal-code">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[0-9]{5}(-[0-9]{4})?"/>

Once again, I apologize for the shotgun blast of code.

Edited by: 911704 on Feb 1, 2012 12:18 PM

Edited by: 911704 on Feb 1, 2012 12:24 PM


  • Correct Answers - 10 points
  • Helpful Answers - 5 points