tags:

views:

45

answers:

2

Hi everyone,

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 perfor sp.append but unfortunately I dont 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.

+4  A: 

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)

Brel
Another possibility is to use a `PrintWriter` and its `println` method, which will automagically append the system-correct line terminator to any string output. In fact, I'd say this is the "standard" way to write lines to an output file.
Carl Smotricz
Awesome worked!
Bilzac
+1  A: 

Modified as suggested by Brel, your text-substituting approach should work, and it will work well enough for simple applications.

If things start to get a little hairier, and you end up wanting to select elements based on their position in the XML structure, and if you need to be sure to change element text but not tag text (think <abc>abc</abc>), then you'll want to call in in the cavalry and process the XML with an XML parser.

Essentially you read in a Document using a DocuemntBuilder, you hop around the document's nodes doing whatever you need to, and then ask the Document to write itself back to file. Or do you ask the parser? Anyway, most XML parsers have a handful of options that let you format the XML output: You can specify indentation (or not) and maybe newlines for every opening tag, that kinda thing, to make your XML look pretty.

Carl Smotricz
thanks for the reply!
Bilzac