Ianthe Ianthe - 4 months ago 24
Java Question

Java : Convert formatted xml file to one line string

I have a formatted XML file, and I want to convert it to one line string, how can I do that.

Sample xml:

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>Basic XML</title>
<price>100</price>
<qty>5</qty>
</book>
<book>
<title>Basic Java</title>
<price>200</price>
<qty>15</qty>
</book>
</books>


Expected output

<?xml version="1.0" encoding="UTF-8"?><books><book> <title>Basic XML</title><price>100</price><qty>5</qty></book><book><title>Basic Java</title><price>200</price><qty>15</qty></book></books>


Thanks in advance.

ant ant
Answer
//filename is filepath string
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line;
StringBuilder sb = new StringBuilder();

while((line=br.readLine())!= null){
    sb.append(line.trim());
}

using StringBuilder is more efficient then concat http://kaioa.com/node/59

Comments