2

I use Axis to get some response through a remote Web Service. After receiving the response, I would convert the response string to XML Document in order for the subsequent process. Finally, my program would convert the processed Document to String as return.

Sometime I would receive some tag like <bla></bla>, a pair of tag with nothing. After converting the String to Document and getting through the process, the result would be converted to String finally.

But the <bla></bla> would become <bla/> automatically.

How do I keep the <bla></bla> the same without any change?

The following code is what I used to do the conversion.

public class TagMove {
   public static void main(String[] args)  throws Exception {
       String strA = "<STUDENT><NAME>Arthur</NAME><AGE></AGE></STUDENT>";
       Document docA = convertStringToDocument(strA, "UTF8");
       docA.setXmlStandalone(true);
       System.out.println(convertDocument2String(docA));
   }

   public static String convertDocument2String(Document doc) throws Exception {
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
       StreamResult result = new StreamResult(new StringWriter());
       DOMSource source = new DOMSource(doc);
       transformer.transform(source, result);
       String xmlString = result.getWriter().toString();
       return xmlString;
   }
   public static Document convertStringToDocument(String xmlString, String encoding) {
       try {
           DocumentBuilderFactory FACTORY =    DocumentBuilderFactory.newInstance();
           DocumentBuilder builder = FACTORY.newDocumentBuilder();
           Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes(encoding))));
           return doc;
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
   }
}
2
  • 2
    Just in case you didn't know, <bla></bla> and <bla/> are semantically equivalent. If the XML is only meant to be read by computers, you could leave it like that without risk Commented Dec 11, 2015 at 16:19
  • I know. But I can not guarantee that the caller of my program would treat it as XML. Because my program's role is like a EAI hub, there would be lots of clients. Commented Dec 11, 2015 at 16:34

1 Answer 1

2

You can try to play with output format method

transformer.setOutputProperty(OutputKeys.METHOD, "html");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.