java - 将字符串转换为 XML 文档而不更改结束标记

标签 java xml

我使用 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/

相关文章:

java - 在 Java 中实现跳转表

python - 在 python 中解析 xml

java - 对象属性共享同一个实例

java - 两个 TextView 导致一个 Activity

java - 如何使用 Java.awt 镜像图像

java - 使用哪个 jar 连接到 MS SQL 服务器

xml - XSD 允许同一元素同时包含 simpleType 和 complexType 内容吗?

java - 将无效的xml元素添加到xml文档java

c# - 将 XslCompiledTransform 与 cdata-section-elements 结合使用

javascript - 通过 AJAX 发送的 JSON 是否会在某个时刻格式化为 XML?