3
votes

I am trying to dynamically generate XML schema using Xerces-J and getting the following error, appreciate any help regarding it.

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);

DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();

Element schema = doc.createElement("xs:schema");           
schema.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
doc.appendChild(schema);

Element e = doc.createElement("xs:element");            
e.setAttribute("name", "test");
e.setAttribute("type", "xs:string");

schema.appendChild(e);

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.INDENT, "yes");

//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);

trans.transform(source, result);
String xmlString = sw.toString();

System.out.println(xmlString);

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

Schema schema1 = schemaFactory.newSchema(source);

Output is

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="test" type="xs:string"/>
</xs:schema>

org.xml.sax.SAXParseException: s4s-elt-schema-ns: The namespace of element 'xs:schema' must be from the schema namespace, 'http://www.w3.org/2001/XMLSchema'.

2

2 Answers

2
votes

When building a DOM, you don't specify namespaces as attributes. Instead, use the version of createElement() that takes two parameters: the first is the namespace URI, the second is the element's qualified name.

Note also that the prefix of a qualified name will automatically be matched to the namespace URI. If you want, you could eliminate the prefix altogether, and the serializer will do the right thing (either creating an xmlns attribute without prefix, or generating a prefix).

0
votes

I had the similar problem and found the Apache Commons XMLSchema