Arthur
Arthur

Reputation: 151

Convert String to XML Document without changing end tag

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;
   }
}

Upvotes: 2

Views: 220

Answers (1)

AdamSkywalker
AdamSkywalker

Reputation: 11609

You can try to play with output format method

transformer.setOutputProperty(OutputKeys.METHOD, "html");

Upvotes: 2

Related Questions