Categories
General

Validating an XML document against a schem

To validate the XML files I am generating against a schema, I used this very simplistic code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);

factory.setNamespaceAware(true);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

Schema schema = schemaFactory.newSchema(new File("my-schema.xsd"));

factory.setSchema(schema);

Document doc = factory.newDocumentBuilder().parse(new File("my-file.xml"));

If anything is invalid, exceptions are thrown.

Be sure to include the following line:

factory.setNamespaceAware(true);

otherwise you will get this cryptic error:
cvc-complex-type.3.2.2: Attribute 'xsi:noNamespaceSchemaLocation' is not allowed to appear in element ...

Share
Categories
Java

Java 1.5 bug – Transfromer needs some coaxing

My current class assignment requires me to produce XML. Not so wisely I am using DOM to build the Document, but then the benefit comes in the form of Java’s Transformer object. What a fine object it is – the one and only meant to commit your XML to a file.
Still, what used to work in Java 1.4 somehow broke in Java 1.5; Transformer no longer obeys the following instructions that are meant to set it to indent its XML output:

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");

Naturally, I Googled this issue and as usual, the best place to find an answer were the Sun Java Forums. Many people offered help but the one that actually cracked this problem was one xuemingshen in this thread: His solution — use an OutputStreamWriter object as the parameter for the StreamResult that will be used by the Transfomer when it performs the transformation. The code:


try
{
Source source = new DOMSource(myDOMDocument);
File outputFile = new File(fileName + ".xml");
FileOutputStream outputStream = new FileOutputStream(outputFile);
Result result = new StreamResult(new OutputStreamWriter(outputStream));

TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute("indent-number", 4);

Transformer transformer = factory.newTransformer();

transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");

transformer.transform(source, result);
}

catch… TransformerConfigurationException, TransformerException, FileNotFoundException

I am using a FileOutputStream object to output to file but an OutputStream object will do.
Thank you xuemingshen !

Share
Categories
Television

Arrested Development – Explained

I saw this posting on the very prosaic bensbargains.net website about ‘Arrested Development’ and for some reason it hit home:

best show on television that no one understands

How true.

Share
Share