Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java xml self-closing tags

My Java program looks like:

public static void main(String[] args) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
        Document document = db.parse(new ByteArrayInputStream("<test><test1></test1></test>".getBytes("UTF-8")));
        StringWriter stringWriter = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        System.out.println(stringWriter.toString());
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

Output is: <test><test1/></test> I want output <test><test1></test1></test>.

Because I'm using JasperReports and html style only allow my wanted output. How to achieve that? Is there any output property of Transformer or any property of DocumentBuilderFactory to do wanted output?

like image 240
zmeda Avatar asked Dec 13 '12 12:12

zmeda


People also ask

Can XML have self closing tags?

All tags in XML or XHTML can be used as self-closing by closing them with (<.. />). HTML5: Using a slash is absolutely optional. HTML4: Using a slash is technically invalid. However, the W3C's HTML validator still accepts it.

How do you end a tag in XML?

The end tag functions exactly like a right parenthesis or a closing quotation mark or a right curly brace. It contains no data of its own; it simply ends the most recent (innermost) tag with the same name. XML requires a matching end tag for each start tag.

Which tags are self closing?

↑ The full list of valid self-closing tags in HTML5 is: area, base, br, col, embed, hr, img, input, keygen, link, meta, param, source, track, and wbr.

Do self contained tags use a closing tag?

HTML Self Closing TagA self closing tags in HTML are the type of HTML tags that need not to be closed manually by its closing tag, which means there is no saperate closing tag for it as </tag>. A few examples of self closing tags are <img />, <input />, <br />, <hr />, etc.


1 Answers

If you add this line before you invoke transformer.transform - the output will be in html style:

transformer.setOutputProperty(OutputKeys.METHOD, "html");
like image 90
Boris Avatar answered Oct 05 '22 17:10

Boris