I have an xml file and String data, I want to add the String in xml file, I am beginner to Java, confusing how to open the xml and append String before xml syntax start. Below is the xml file
<?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";
Final output
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>
CodePudding user response:
Try like this
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.getProperty("line.separator"));
}
mFile.delete();
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(result.toString().getBytes());
fos.flush();
} catch (IOException e) {
//exception handling
}
UPD: added this line result.append(System.getProperty("line.separator"));