Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Convert formatted xml file to one line string

Tags:

java

string

xml

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.

like image 889
Ianthe Avatar asked Apr 01 '11 08:04

Ianthe


People also ask

How do I convert a file to String in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion. String convertDocumentToString(Document doc) : This method will take input as Document and convert it to String.

How do I read an XML String in Java?

In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.

How do I read an XML String in Python?

Example Read XML File in Pythonparse() method, to start parsing. Then, we will get the parent tag of the XML file using getroot() . Then we will display the parent tag of the XML file. Now, to get attributes of the sub-tag of the parent tag will use root[0].


1 Answers

//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

like image 186
ant Avatar answered Sep 20 '22 19:09

ant