Java : Convert formatted xml file to one line string

read xml file as string in java 8
convert xml to string java online
read and write xml file in java
convert xml file to document object in java
convert xml file to string c#
how to read xml file in java
reading through the string in xml format and get the values of elements in java
java create xml 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"?>
       <title>Basic XML</title>
     <title>Basic Java</title>

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.

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

while((line=br.readLine())!= null){

using StringBuilder is more efficient then concat

Java : Convert formatted xml file to one line string?, Java : Convert formatted xml file to one line string? Reader r = new BufferedReader(filename); String ret = ""; while((String s = r.nextLine()  Java : Convert formatted xml file to one line string. Ask Question Asked 8 years, 9 months ago. Converting ISO 8601-compliant String to java.util.Date. 2028.

Run it through an XSLT identity transform with <xsl:output indent="no"> and <xsl:strip-space elements="*"/>

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
    <xsl:output indent="no" />
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
            <xsl:apply-templates select="@*|node()"/>

It will remove any of the non-significant whitespace and produce the expected output that you posted.

Java XML to String, Java examples to read XML file and print XML string to console or write XML to file. 1) Convert XML to String. To convert XML object i.e org.w3c.dom.Document  Sometimes while programming in java, we get String which is actually an XML and to process it, we need to convert it to XML Document (org.w3c.dom.Document).Also for debugging purpose or to send to some other function, we might need to convert Document object to String.

// 1. Read xml from file to StringBuilder (StringBuffer)
// 2. call s = stringBuffer.toString()
// 3. remove all "\n" and "\t": 


I made a small mistake, it is better to use StringBuilder in your case (I suppose you don't need thread-safe StringBuffer)

String to XML and XML to String in Java, For converting xml document to string, we will use DOMSource and Transformer classes as follows : "<Tutorial id=\"1\"><technology>Dot net, Java, Big data, Database</technology>\n"+ or, we can create a sample xml file in the local path and read that. Reading command line arguments in Kotlin. Java XML Formatter. Few days back, I came across a situation where the third party API was returning Document object and XML message as String. So I wrote this simple XmlFormatter class to format the XML with proper indentation and convert Document object to XML String.

Open and read the file.

Reader r = new BufferedReader(filename);
String ret = "";
while((String s = r.nextLine()!=null)) 
return ret;

Java XML Formatter, Java XML Formatter, XML to Document, Document to XML, format xml in java, java pretty eXtensive Markup Language (XML) is one of the popular medium for the XML with proper indentation and convert Document object to XML String​. How can i add new line after each book in user case XML should look as below. Here is our Java program to read XML as String. It contains three example, first, one uses BufferedReader and reads XML like a text file. It's not great because you need to specify character encoding by yourself while XML parser can read it directly from XML header. In this approach, you can build XML string by reading file line by line.

Using this answer which provides the code to use Dom4j to do pretty-printing, change the line that sets the output format from: createPrettyPrint() to: createCompactFormat()

public String unPrettyPrint(final String xml){  

    if (StringUtils.isBlank(xml)) {
        throw new RuntimeException("xml was null or blank in unPrettyPrint()");

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createCompactFormat();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
    catch (Exception e) {
        throw new RuntimeException("Error un-pretty printing xml:\n" + xml, e);
    return sw.toString();

Java Convert String to XML Document and XML Document to String , You can use replaceAll("\n|\r", "") to remove new line characters from String and get it in compact format. Online Multiline to Single Line Converter. Online tool to convert Multiline to Single Line, JSON to One Line and Text to One Line.Multiline Text, JSON, String or XML to Single Line by smart way.

Writing Out a DOM as an XML File (The Java™ Tutorials > Java API , This JAXP Java tutorial describes Java API for XML Processing (jaxp), XSLT, SAX, After you have constructed a DOM (either by parsing an XML file or building it It is basically the same code as was used at the start of the Document Object generated by the parser System.out.println("\n** Parsing error" + ", line " + spe. I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this? String unformattedXml = "<tag><nested>hello</nested></tag>"; String formattedXml = new [UnknownClass]().format(unformattedXml); Note: My input is a String. My output is a String.

How to Read XML File as String in Java? 3 Examples, You can do it in one line if you are fine with using an open source library or you discussed in my earlier post 3 ways to convert InputStream to String in Java. By the way, while reading XML file as String one thing you must  Hi, I have tried the code which you have suggested My question is, after converting the xml string to XML file say A.xml I want to read the A.XML file and append the data (data is in xml string) to the A.XML file

Free Online HTML Formatter, Formats a HTML string/file with your desired indentation level. The formatting rules are not configurable but are already optimized for the best possible output. This article provides utility methods to : For converting xml document to string, we will use DOMSource and Transformer classes as follows : For converting the string to xml document, we can use DocumentBuilderFactory and DocumentBuilder classes. Here is the code for toXmlDocument () method : For this program, we can either hardcode the xml

  • This should not be necessary. Why do you need that?
  • @Tomalak I need that to be pass to a cgi as an input and that cgi only accepts xml in one-line form.
  • @All, thanks a lot for all the answers
  • This will not remove leading/trailing spaces, no?
  • This doesn't respect the encoding mentioned in the XML document, does it?
  • sorry for offtopic comment but that link is expired and redirect users to irrelevant domains.
  • this seems to be a nice way but you did not mention how to run this XSLT in Java?
  • XSLT processing with Java
  • What if there was whitespace between a content element e.g. <text>foo (newline) bar</text>?
  • double spaces, look at expected result, we have e.g. <book> <title> - after book is space. I don't think @sprenna want do something with spaces.
  • It looks like an error in the example, b/c the other <book><title> combinations have no space in between
  • that is a typo, there shouldn't be any space in between. sorry for that.