Reading XML, replacing text, and writing to the same XML file via Java

I'm currently trying to make something very simple. I am viewing an XML document for a specific phrase, on which I am trying to replace it. The problem I am facing is that when I read the lines, I store each line in a StringBuffer. When I write this to a document, everything is written on one line.

Here is 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 suppose I need a new line character when I prefer sb.append, but unfortunately I don't know which character to use, since "\ n" does not work.

Thanks in advance!

PS I decided that there should be a way to use Xalan to format the XML file after I write it or something else. Not sure how to do this.

+3
3

, , , , . : Windows , , unix . , "line.separator":

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

stringbuffer:

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

, Brel, , .

, , XML, , (think <abc>abc</abc>), XML XML.

, Document DocuemntBuilder, , , , Document . ? , XML , XML: ( ) , , , , XML .

+1

Sb StringBuffer, . while:

StringBuffer sb =  new StringBuffer();
0

Source: https://habr.com/ru/post/1753349/


All Articles