Search code examples
javaxmlxalan

Read XML, Replace Text and Write to same XML file via Java


Currently I am trying something very simple. I am looking through an XML document for a certain phrase upon which I try to replace it. The problem I am having is that when I read the lines I store each line into a StringBuffer. When I write the it to a document everything is written on a single line.

Here my code:

File xmlFile = new File("abc.xml")
BufferedReader br = new BufferedReader(new FileReade(xmlFile));
String line = null;
while((line = br.readLine())!= null)
{
    if(line.indexOf("abc") != -1)
    {
        line = line.replaceAll("abc","xyz");
    }         
    sb.append(line);                
}
br.close();

BufferedWriter bw = new BufferedWriter(new FileWriter(xmlFile));
bw.write(sb.toString());
bw.close();

I am assuming I need a new line character when I prefer sb.append but unfortunately I don't know which character to use as "\n" does not work.

Thanks in advance!

P.S. I figured there must be a way to use Xalan to format the XML file after I write to it or something. Not sure how to do that though.


Solution

  • The readline reads everything between the newline characters so when you write back out, obviously the newline characters are missing. These characters depend on the OS: windows uses two characters to do a newline, unix uses one for example. To be OS agnostic, retrieve the system property "line.separator":

    String newline = System.getProperty("line.separator");
    

    and append it to your stringbuffer:

    sb.append(line).append(newline);