在 xml 文件中追加字符串

Append the String in xml file

我有一个xml文件和字符串数据,我想在xml文件中添加字符串,我是初学者Java,不知道如何打开[=20] =] 并在 xml 语法开始之前附加字符串。 下面是 xml 文件

<?xml version="1.0"?>
-<AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.02">
-<Fr>
-<FIId>
-<Fin>
<BIC>AAA</BIC>
</Fin>
</FIId>
</Fr>
</AppHdr>

String value="Hello Append with xml";

最终输出

Hello Append with xml<?xml version="1.0"?>
-<AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.02">
-<Fr>
-<FIId>
-<Fin>
<BIC>AAA</BIC>
</Fin>
</FIId>
</Fr>
</AppHdr>

这样试试

try {
  File mFile = new File("C:\name.xml");//path to file with name of file
  FileInputStream fis = new FileInputStream(mFile);
  BufferedReader br = new BufferedReader(new InputStreamReader(fis));
  StringBuilder result = new StringBuilder("Hello Append with xml");
  String line = "";
  while( (line = br.readLine()) != null){
    result.append(line);
    result.append(System.lineSeparator());
  }

  mFile.delete();
  FileOutputStream fos = new FileOutputStream(mFile);
  fos.write(result.toString().getBytes());
  fos.flush();
} catch (IOException e) {
  //exception handling
}

UPD:添加了这一行result.append(System.getProperty("line.separator")); UPD:将此 System.getProperty("line.separator") 更改为 System.lineSeparator()