Skip to Main Content

DevOps, CI/CD and Automation

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

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

914707Feb 1 2012 — edited Feb 2 2012
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 java.io.File;
import java.io.IOException;
import java.io.StringWriter;

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.transform.stream.StreamResult;
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) {
			temp.appendChild(doc.createTextNode(text));
		}
		element.appendChild(temp);
		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 = 
			"http://java.sun.com/xml/jaxp/properties/schemaSource";
		String filePath = new File(".").getCanonicalPath();
		filePath+="/XMLFiles/";
		File schemaFile = new File(filePath + "AddressSchema.xsd");
		Element root = null;
		Element name = null;
		
		try {					
			//Build a document parser
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);	
			//Set up schema for factory
			dbf.setAttribute(JAXP_SCHEMA_SOURCE, schemaFile);
			db = dbf.newDocumentBuilder();
			doc = db.newDocument();	
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		//Add items to doc in order to validate with schema.
		try {
			
			root = doc.createElement("address");
			doc.appendChild(root);
			
			//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) {
			System.out.println(e.getMessage());
		} 
		
		// build an XSD-aware SchemaFactory
		SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );

		// hook up ErrorHandler implementation.
		schemaFactory.setErrorHandler(new ErrorHandler() {
			@Override
			public void error(SAXParseException ex) throws SAXException {  throw ex;}
			@Override
			public void fatalError(SAXParseException ex) throws SAXException {  throw ex;}
			@Override
			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
			e1.printStackTrace();
		}
		
		//Copy result to string and print
		String xmlString = result.getWriter().toString();
		System.out.println(xmlString);
		
		//The problem below here fails.
		try {
			validator.validate(new DOMSource (doc));
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		
	}
	
	public static void main (String args[]) throws IOException, SAXException {
		
		try {
			ReplicationBugValidationWithNewDom d = new ReplicationBugValidationWithNewDom();					
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;
	}

}
The Output:

Before validation, Document has address
<?xml version="1.0" encoding="UTF-8"?><address>
<name>
<title>Mr.</title>
<first-Name>Billy</first-Name>
<last-Name>Madison</last-Name>
</name>
<street>111 blah street</street>
<city>Cashville</city>
<state>VA</state>
<postal-code>99933-2244</postal-code>
</address>
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.


Thoughts?

Here is AddressSchema.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="address">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="name"/>
<xsd:element ref="street"/>
<xsd:element ref="city"/>
<xsd:element ref="state"/>
<xsd:element ref="postal-code"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

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

<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:simpleType>
<xsd:restriction base="xsd:string">
<xsd:length value="2"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>

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

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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 1 2012
Added on Feb 1 2012
12 comments
846 views