将String转换为XML Document而不更改结束标记

时间:2015-12-11 16:12:51

标签: java xml

我使用Axis通过远程Web服务获得一些响应。 收到响应后,我会将响应字符串转换为XML Document,以便进行后续处理。 最后,我的程序会将处理过的Document转换为String作为返回。

有时我会收到一些像<bla></bla>这样的标签,一对没有标签的标签。 将String转换为Document并完成整个过程后,结果最终将转换为String。

<bla></bla>会自动成为<bla/>

如何保持<bla></bla>相同而不做任何更改?

以下代码是我用来进行转换的代码。

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

1 个答案:

答案 0 :(得分:2)

您可以尝试使用输出格式方法

transformer.setOutputProperty(OutputKeys.METHOD, "html");
相关问题