Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

xml

xalan

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.

like image 478
Bilzac Avatar asked May 03 '26 01:05

Bilzac


2 Answers

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);
like image 138
Brel Avatar answered May 05 '26 15:05

Brel


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.

like image 37
Carl Smotricz Avatar answered May 05 '26 16:05

Carl Smotricz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!