I have a formatted XML file, and I want to convert it to one line string, how can I do that.
Sample xml:
// 1. Read xml from file to StringBuilder (StringBuffer)
// 2. call s = stringBuffer.toString()
// 3. remove all "\n" and "\t":
s.replaceAll("\n","");
s.replaceAll("\t","");
edited:
I made a small mistake, it is better to use StringBuilder in your case (I suppose you don't need thread-safe StringBuffer)
In java 1.8 and above
BufferedReader br = new BufferedReader(new FileReader(filePath));
String content = br.lines().collect(Collectors.joining("\n"));
I guess you want to read in, ignore the white space, and write it out again. Most XML packages have an option to ignore white space. For example, the DocumentBuilderFactory has setIgnoringElementContentWhitespace for this purpose.
Similarly if you are generating the XML by marshaling an object then JAXB has JAXB_FORMATTED_OUTPUT
Underscore-java library has static method U.formatXml(xmlstring). I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
import com.github.underscore.lodash.Xml;
public class MyClass {
public static void main(String[] args) {
System.out.println(U.formatXml("<a>\n <b></b>\n <b></b>\n</a>",
Xml.XmlStringBuilder.Step.COMPACT));
}
}
// output: <a><b></b><b></b></a>
FileUtils.readFileToString(fileName);
link
Open and read the file.
Reader r = new BufferedReader(filename);
String ret = "";
while((String s = r.nextLine()!=null))
{
ret+=s;
}
return ret;