我使用 Axis 通过远程 Web 服务获取一些响应。 收到响应后,我会将响应字符串转换为XML文档,以便后续处理。 最后,我的程序会将处理后的文档转换为字符串作为返回。
有时我会收到一些标签,例如 <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;
}
}
最佳答案
你可以尝试用输出格式的方法来玩
transformer.setOutputProperty(OutputKeys.METHOD, "html");
关于java - 将字符串转换为 XML 文档而不更改结束标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34227873/