【问题标题】:how to append text in top and end of the .xml file using java?如何使用 java 在 .xml 文件的顶部和末尾附加文本?
【发布时间】:2016-09-03 07:00:42
【问题描述】:

我有一个下面的 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<reRoot>
<reNode> world</reNode>
</reRoot>

我想在添加如下文本后显示我的 xml 文件,

Linesaddedbeforexml
<?xml version="1.0" encoding="UTF-8"?>
    <reRoot>
    <reNode> world</reNode>
    </reRoot>
Linesaddedafterxml

如何使用 java 实现这一点,我尝试了 Filewriter,但写入后对齐不正确。, 需要示例逻辑代码的解决方案帮助。

【问题讨论】:

    标签: java file parsing io


    【解决方案1】:

    该主题的答案已发布在另一个主题上,这将非常有帮助。

    how to append text in top and end of the .xml file using java?

    【讨论】:

      【解决方案2】:

      使用 Filewritter 写入文本后,您可以按如下方式对 xml 进行格式化

      public static String prettyFormat(String input) {
          Source xmlInput = new StreamSource(new StringReader(input));
          StringWriter stringWriter = new StringWriter();
          try {
              TransformerFactory transformerFactory = TransformerFactory.newInstance();
              Transformer transformer = transformerFactory.newTransformer();
              transformer.setOutputProperty(OutputKeys.INDENT, "yes");
              transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", 2);
              transformer.transform(xmlInput, new StreamResult(stringWriter));
      
              String pretty = stringWriter.toString();
              pretty = pretty.replace("\r\n", "\n");
              return pretty;              
          } catch (Exception e) {
              throw new RuntimeException(e);
          }
      }
      

      【讨论】:

      • 在哪里提到xml和xsl文件路径?@Jekin Kalariya
      • Vidya 这里的方法参数将是你的 xml 字符串
      猜你喜欢
      • 1970-01-01
      • 2011-04-13
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 2011-09-06
      相关资源
      最近更新 更多