Java XML dom: prevent collapsing empty element - java

I use the javax.xml.parsers.DocumentBuilder, and want to write a org.w3c.dom.Document to a file.
If there is an empty element, the default output is a collapsed:
<element/>
Can I change this behavior so that is doesn't collapse the element? I.e.:
<element></element>
Thanks for your help.

This actualy depends on the way how you're writing a document to a file and has nothing to do with DOM itself. The following example uses popular Transformer-based approach:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document = factory.newDocumentBuilder().newDocument();
Element element = document.createElement("tag");
document.appendChild(element);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
It outputs <tag></tag> as you're expecting. Please note, that changing the output method has other side effects, like missing XML declaration.

Related

Disable Indent in JAXP when transform XML

I am using JAXP to convert DOM tree to XML. I do not want any intends in my result XML.
This is my code:
root.normalize();
DOMSource domSource = new DOMSource(root);
StreamResult result = new StreamResult(outputStream);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.transform(domSource, result);
It works nice if source is not intended and result is also not intended,
If the source XML file is pretty formatted, then "INDENT = no" takes no effect.
The transformed XML file is still indented but I do not want that.
This input generate correct output with no intends.:
<InitMessage xmlns="http://www.test.com/"><operation>while</operation><part1>6</part1><part2>2</part2><part3>5</part3><part4>1</part4></InitMessage>
But this one no and I still got pretty printed intended xml in my output (one line).
<InitMessage xmlns="http://www.test.com/">
<operation>while</operation>
<part1>6</part1>
<part2>2</part2>
<part3>5</part3>
<part4>1</part4>
</InitMessage>
Setting INDENT to no only indicates that the processor is not allowed to add
additional whitespace, not that it will strip existing whitespace.

JAVA 8 xml pretty output not working properly

I try to save Document to the XML in pretty output. But problem is every new element start from line of pervious element end tag.
Example:
<?xml version="1.0" encoding="UTF-8"?><report>
<jiraentry category="SERVICE & ASSET" component="DOCMAN" priority="10" summary="Bug Generated By, UNCHECKED_ACCESS">Tool:UNCHECKED_ACCESS Date:2015-11-12
</jiraentry>
You can see that and text in print in pervious line.Here is the below my Java code which i used to save xml by using transformer.
//normalize the xml file
root.getDocumentElement().normalize();
//remove standalone no
root.setXmlStandalone(true);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", new Integer(0));//add intend to the new line
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(root);
StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(this.outpath), "UTF-8"));//save the file
transformer.transform(source, result);
Any one can suggest me to make this more pretty and clear.
You need to set the indent amount for the transformer as shown in the snippet below:
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Useful Reference: Similar Question

Java XML Transformer : Empty elements in long notation instead of short

I have created a conversion tool to add some information to an existing xml file.
This is done by using DOM and the Transformer class.
The output file will be processed by third party software.
This TPS needs the empty tags from the input and outputfile in Long Notation.
Unfortunately, transformer class always change them to short notation.
Is there a way to prevent this from happenning?
I have been searching various sites, but haven't found a solution that really fits my needs.
Please help,
Thanks,
Kind regards,
Maarten
You can transform the DOM to StAXResult.
For instance,
XMLOutputFactory factory=XMLOutputFactory.newFactory();
XMLStreamWriter writer=factory.createXMLStreamWriter(System.out);
StAXResult result=new StAXResult(writer);
trans.transform(new DOMSource(doc),result);
XMLOutputFactory factory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = factory.createXMLStreamWriter(System.out);
StAXResult result = new StAXResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), result);

Header Tag in XML using JAXB

Right now I am getting this as an XML output from my JAXB Marshaller
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><create></create>
But I want my root element as:
<create xmlns="http://ws.abc.com" xmlns:doc="http://ws.abc.com">
Do I need to modify this using parsers, Or is there any annotation available.
You can set the following property on the Marshaller to remove the header:
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
For More Information
http://blog.bdoughan.com/2011/08/jaxb-and-java-io-files-streams-readers.html
I've used a Transformer in the past. You'd want something like the following sample code:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StreamResult transformedDoc = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(content); // Where content is a org.w3c.dom.Document object.
transformer.transform(source, transformedDoc);
So maybe do your marshalling and then process. Not sure if this is the best approach but it would work.

Transformer's transform causes a fatal error, why?

I've built a document using JAXP like this:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("Root");
for (MyObject o : myCollection) {
Element entry = document.createElement("Entry");
Element entryItem = document.createElement("EntryItem");
entryItem.appendChild(document.createTextNode(o.getProperty()));
entry.appendChild(entryItem);
rootElement.appendChild(entry);
}
document.appendChild(rootElement);
Now, when I try to output the XML for the document like this:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
System.out.println(result.getWriter().toString());
It falls apart on the transformer.transform line with the following error:
FATAL ERROR: 'java.lang.NullPointerException'
:null
How do I go about debugging this? I've made sure that transformer, source and result aren't null.
I'm guessing that this:
entryItem.appendChild(document.createTextNode(o.getProperty()));
created a text node with a null value. Looking at Xerces' code (which is the default JAXP implementation shipped with Oracle's JDK 1.6), I see no null validation done at the time of constructing the text node. I suspect that that, later, makes the Transformer die.
Either that, or there's some JAXp configuration problem.
You may wish to set the jaxp.debug system property (available JDK 1.6+) to get some JAXP tracing information.
--How about the document?
Ooops sorry, obviously the second part follows the first :) Which parser are you using?

Categories