Dynamically generating XML Schema - java

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'.

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).

I had the similar problem and found the Apache Commons XMLSchema

Related

Java DOM Transformer - XML creation doesn't replace apostrophe and quotes in the final xml

I'm trying to create an XML and return it as a response to the caller based on the input.
The transformer works as expected for most parts, but it doesn't convert apostrophe and quotes to their XML equivalent. Below is the code I'm using
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("template");
doc.appendChild(rootElement);
/* Adding attendant ID */
Element line = doc.createElement("line");
line.appendChild(doc.createTextNode("----&----<------>------'-----\"--------"));
Attr Attr1 = doc.createAttribute("Attr1");
Attr1.setValue("attribute value 1");
line.setAttributeNode(Attr1);
Attr Attr2 = doc.createAttribute("Attr2");
Attr2.setValue("attribute value 2");
line.setAttributeNode(Attr2);
rootElement.appendChild(line);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
// Output to String
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String strResult = writer.toString();
//return escapeXml(strResult);
System.out.println(strResult);
Resulting output
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<template>
<line Attr1="attribute value 1" Attr2="attribute value 2">----&----<------>------'-----"--------</line>
</template>
Expected Result
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<template>
<line Attr1="attribute value 1" Attr2="attribute value 2">----&----<------>------&apos;-----"--------</line>
</template>
Initially I thought could escape those character before sending it as input to transformer, but it replaced all the ampersand to their equivalent "&". If I replace the apostrophe or quotes after the final XML is created, it replaces attributes as well.
I'm thinking we could solve this in 2 ways
I could transform the & , < , > , ' , " before adding to node and transformer ignores it
Give explicit directions to transformer to convert ' , " them to their XML equivalent.
Currently I'm unaware of how to achieve these. Could someone help me on this or if a better solution to create a valid XML would hugely be appreciated.
Thanks.
Why do you want quotation marks and apostrophes to be escaped? XML doesn't require them to be escaped (except in attributes where they conflict with the attribute delimiters). The serializer knows what it's doing: trust it.

DocumentBuilderFactory removing namespaces, even with #setNamespaceAware

I'm trying to convert an XML string to a Document, do some DOM manipulation, then convert it back to a string. But I'm having trouble getting the namespaces to be retained after the tranformation. I'd like to keep the namespace for child elements which have the same namespace as the parent.
I'm running the following simple code to test:
final String test = "<element xmlns:xc=\"urn:myNamespace\">\n"
+ "\t<child xmlns:xc=\"urn:myNamespace\">\n"
+ "\t\t<attribute>value</attribute>\n"
+ "\t</child>\n"
+ "</element>\n";
System.out.println(test);
final DocumentBuilderFactory documentBuilderFactory = mentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
final Document testDoc = documentBuilderFactory
.newDocumentBuilder()
.parse(new ByteArrayInputStream(test.getBytes(StandardCharsets.UTF_8)));
final StringWriter stringWriter = new StringWriter();
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(new DOMSource(testDoc), new StreamResult(stringWriter));
System.out.println(stringWriter.toString());
The output is:
<element xmlns:xc="urn:myNamespace">
<child xmlns:xc="urn:myNamespace">
<attribute>value</attribute>
</child>
</element>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<element xmlns:xc="urn:myNamespace">
<child>
<attribute>value</attribute>
</child>
</element>
I'm using Java 7. Is there any way to keep the namespace in the child element?

How do I add a namespace prefix to an XML DOM object?

I am trying to build an XML document using a specific namespace. The final document I am trying to generate is supposed to look like this:
<m:documentObject xmlns:m="http://www.myschema.com">
<sender>token</sender>
<receiver>token</receiver>
<payload>token</payload>
</m:documentObject>
Here is what i have so far.
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element requestElement = document.createElementNS("http://www.myschema.com", "documentObject");
document.appendChild(requestElement);
Element sender = document.createElement("sender");
requestElement.appendChild(sender);
Text senderText = document.createTextNode("Xmlsender");
sender.appendChild(senderText);
Element receiver = document.createElement("receiver");
requestElement.appendChild(receiver);
Text receiverText = document.createTextNode("Xmlreceiver");
receiver.appendChild(receiverText);
Element payload = document.createElement("payload");
requestElement.appendChild(payload);
Text payloadText = document.createTextNode("Xmlpayload");
payload.appendChild(payloadText);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(requestElement);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.transform(source, result);
String xmlString = sw.toString();
System.out.println(xmlString)
For some reason when I run the above the schema comes out without the prefix. As shown below:
<?xml version="1.0" encoding="utf-8"?>
<documentObject xmlns="http://www.myschema.com">
<sender>Xmlsender</sender>
<receiver>Xmlreceiver</receiver>
<payload>Xmlpayload</payload>
</documentObject>
What do I need to do so that XML is exactly as shown in the first XML example with the namespace prefix and the tags to have the namespace prefix?
I am trying to create an XML string which will be used for a Spring-WS webservice which expects a JAXB object which is in the format shown in the first example.
You can use setPrefix.
But it is better to create the root element like this:
document.createElementNS("http://www.myschema.com", "m:documentObject");
Note also that passing null to createElement is a supported way of forcing a null namespace. In your original example this would however not work because your document element effectively forces a default namespace by combining a namespace URI with no prefix.

How to create attribute (xmlns:xsd) to XML node in Java?

I am currently creating an XML document in Java. The document should have the following structure:
<?xml version="1.0" ?>
<Cancelacion xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
RfcEmisor="VSI850514HX4"
Fecha="2011-11-23T17:25:06"
xmlns="http://cancelacfd.sat.gob.mx">
<Folios>
<UUID>BD6CA3B1-E565-4985-88A9-694A6DD48448</UUID>
</Folios>
</Cancelacion>
I want to know if there is a special way to create the attributes with form xmlns:xsd?
I am currently declaring this attribute like this:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");
doc.setXmlStandalone(true);
Element cancelacion = doc.createElement("Cancelacion");
cancelacion.setAttribute("xmlns", "http://cancelacfd.sat.gob.mx");
cancelacion.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
cancelacion.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
cancelacion.setAttribute("RfcEmisor", rfc);
cancelacion.setAttribute("Fecha", fecha);
The solution my problem is to write the code as follows:
//Crear un document XML vacío
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
DOMImplementation domImpl = docBuilder.getDOMImplementation();
Document doc = domImpl.createDocument("http://cancelacfd.sat.gob.mx", "Cancelacion", null);
doc.setXmlVersion("1.0");
doc.setXmlStandalone(true);
Element cancelacion = doc.getDocumentElement();
cancelacion.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xsd","http://www.w3.org/2001/XMLSchema");
cancelacion.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
cancelacion.setAttribute("RfcEmisor", rfc);
cancelacion.setAttribute("Fecha", fecha);
Element folios = doc.createElement("Folios");
cancelacion.appendChild(folios);
for (int i=0; i<uuid.length; i++) {
Element u = doc.createElement("UUID");
u.setTextContent(uuid[i]);
folios.appendChild(u);
}
Why should the document have your proposed structure? You're declaring namespaces with prefixes, but your example output doesn't include any elements in those namespaces. Those declarations are therefore unnecessary.
First, understand that xmlns (or xmlns:prefix) is the reserved XML pseudo-attribute for declaring namespaces. It's not a normal attribute. Second, the location of namespace declarations in the document shouldn't concern you, as long as you're creating elements in the desired namespaces in the first place.
Let the serializer decide where to place the namespace declarations.
Register an element in the correct namespace like this:
Element cancelacion = doc.createElementNS(
"http://cancelacfd.sat.gob.mx", "Cancelacion");
doc.appendChild(cancelacion);
Element child = doc.createElementNS("http://cancelacfd.sat.gob.mx",
"SomeChild");
cancelacion.appendChild(child);
When serialized:
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(System.out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.transform(domSource, streamResult);
Result:
<Cancelacion xmlns="http://cancelacfd.sat.gob.mx">
<SomeChild/>
</Cancelacion>
Notice that Cancelacion and SomeChild were created in exactly the same way, but only Cancelacion contains the namespace declaration (because the declaration applies for all descendants). The serializer handled this for us.
Warning: What follows is a hack. I do not recommend using it. It will probably get you into trouble. You should probably stop reading. But...if you have no choice, it might work.
If you're desperate, you could manually splice in the unused namespaces. (Treating XML as a string is almost always a bad idea.)
First, save the result in an OutputStream that can be converted to a String:
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.transform(domSource, streamResult);
Then jam the namespace declarations in there without any regard for what is good, right, and decent:
String[] parts = out.toString().split("\\\">", 2);
String result = parts[0] +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + parts[1];
xmlns:xsd is not an attribute, its a namespace declaration.
The DOM should create these declarations as and when they are needed.
Using the createElementNS and createAttributeNS methods will result in namespace declarations being created, but you need to understand XML namespaces.
In your example, the namespaces bound to xsd and xsi are not used so are superfluous. However, the Cancelacion element is in the default namespace which is defined by the xmlns="http://cancelacfd.sat.gob.mx" declaration in the XML you have provided.
So you should use:
doc.createElementNS("http://cancelacfd.sat.gob.mx", "Cancelacion");
to create that. Note that the namespace prefix (or lack thereof) is irrelevant as far as the meaning of the document is concerned.
in my code, I wrote :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element spectraexchage = document.createElementNS("http://www.lstelcom.com/Schema/SPECTRAexchange", "SPECTRAEXCHANGE");
spectraexchage.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
spectraexchage.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
spectraexchage.setAttribute("version", "2.4.28");
document.appendChild(spectraexchage);
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
output :
<SPECTRAEXCHANGE xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4.28" xmlns="http://www.lstelcom.com/Schema/SPECTRAexchange">

Java DOM XML is skipping xmlns properties

I need to generate an xml file in Java, so I chose to use DOM (until there everything is ok), here is the root tag of what i need to create
<?xml version="1.0" encoding="utf-8"?>
<KeyContainer Version="1.0" xmlns="urn:ietf:params:xml:ns:keyprov:pskc:1.0" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xml="http://www.w3.org/XML/1998/namespace">
Here is my source code
PrintWriter out = new PrintWriter(path);
Document xmldoc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
Element e = null;
Node n = null;
xmldoc = impl.createDocument(null, "KeyContainer", null);
/* Noeuds non bouclés */
Element keycontainer = xmldoc.getDocumentElement();
keycontainer.setAttributeNS(null, "Version", "1.0");
keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ds","http://www.w3.org/2000/09/xmldsig#");
keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xml", "http://www.w3.org/XML/1998/namespace");
keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:ietf:params:xml:ns:keyprov:pskc:1.0");
/* Non relevant Info*/
DOMSource domSource = new DOMSource(xmldoc);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
serializer.setOutputProperty(OutputKeys.VERSION,"1.0");
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
serializer.setOutputProperty(OutputKeys.STANDALONE,"yes");
serializer.transform(domSource, streamResult);
And here is what I get
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<KeyContainer xmlns="" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Version="1.0">
Problem is the xmlns property is empty, and xmlns:xml is missing, what can I do to get all information ?
Thanks a lot stackoverflow
(PS : Got NAMESPACE_ERR if anything else than "http://www.w3.org/2000/xmlns/" in NamespaceURI field)
Two things are required to get rid of xmlns=""
Create the Document with the desired namespace URI as such:
xmldoc = impl.createDocument("urn:ietf:params:xml:ns:keyprov:pskc:1.0", "KeyContainer", null);
Remove the following line as it is now unnecessary:
keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:ietf:params:xml:ns:keyprov:pskc:1.0");
Regarding the xmlns:xml attribute, the API is silently dropping it. See line 173 of NamespaceMappings. A bit of research turns up that the behavior of declaring that particular namespace is undefined and is not recommended.
To make DOM namespace aware, do not forget to enable it in the documentbuilderfactory using the setNamespaceAware method.

Categories

Resources