Hello,
Would gladly appreciate it if anyone can help me out here. I'm using JDOM beta 8 and Xerces (either 1.44 or 2.01 - if any of them works with this!) to validate an xml schema. Below are the codes and further below the schema file. However, it keeps returning me an error "Element type "book" must be declared". It seems that a lot of people have been getting this error as well... can someone help? Thanks!
Smeng
import java.io.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.XMLOutputter;
import org.jdom.input.SAXBuilder;
import org.jdom.JDOMException;
public class translator
{
public static void main(String args[])
{
Document doc = translateTo("book", "D:\\xsd\\test.xsd");
XMLOutputter outputter = new XMLOutputter();
try
{
outputter.output(doc, System.out);
}
catch (IOException ioex)
{
ioex.printStackTrace();
}
boolean isValid = valMsg(doc);
if (isValid)
{
System.out.println("Message is true...");
}
else
{
System.out.println("Message is false...");
}
}
public static Document translateTo(String rootTag, String schema)
{
int intStrPos = 0;
int intSize = 0;
int intEndPos = 0;
String tagvalue = null;
Namespace xsd = Namespace.getNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
Element root = new Element(rootTag);
root.addNamespaceDeclaration(xsd);
root.setAttribute("noNamespaceSchemaLocation", schema, xsd);
Document doc = new Document(root);
Element element = new Element("title");
element.setText("Title appears here");
root.addContent(element);
element = new Element("contents");
element.setText("Contents appears here");
root.addContent(element);
return doc;
}
public static boolean valMsg(Document xmlbody)
{
try
{
SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", true);
builder.setFeature("http://xml.org/sax/features/namespaces", true);
builder.setFeature("http://apache.org/xml/features/validation/schema", true)
builder.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
XMLOutputter xmlOut = new XMLOutputter();
String strXML = xmlOut.outputString(xmlbody);
StringReader strReader = new StringReader(strXML);
Document doc = builder.build(strReader);
System.out.println("No problems building... so return true");
return true;
}
catch (JDOMException jdomex)
{
System.out.println("validation failed at " + jdomex);
return false;
}
}
}
The schma file: test.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema/" elementFormDefault="qualified">
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element ref="title"/>
<xs:element ref="contents"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>