0

I wrote code below to get XML output.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();

Element element = document.createElement("Test");
Text text = document.createTextNode("");
element.appendChild(text);
document.appendChild(element);

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);

What I got is

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Test/>

What I want to get is

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Test></Test>

How can I do this?

Many thanks.

3
  • 2
    why do you want that? It should be the same thing in all practical uses. Commented Oct 7, 2013 at 12:57
  • 1
    The meaning of <Test/> and <Test></Test> is the same Commented Oct 7, 2013 at 12:58
  • I know they are the same in practical use. But I have to do this to satisfy a ridiculous program requirement. :-( Commented Oct 7, 2013 at 13:09

1 Answer 1

2

There is no clean way to do this..

If you feel comfortable to use duct-tape solutions, you could let your transformer output html instead of xml:

transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "html");

But again, I have to point out that this is not a clean solution, but it did the trick for me as I was stuck with a similar problem

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.