Suppose yous own got an XML file in addition to yous simply desire to read in addition to display the whole file every bit String inwards Java, may live on for debugging purpose. If yous are wondering how to exercise that inwards Java, good at that topographic point are many ways to read XML every bit String inwards Java. You tin exercise it inwards i describe of piece of employment if yous are fine amongst using an opened upwards origin library or yous tin exercise it inwards a span of lines of code inwards center Java every bit well. Since an XML file is likewise a file, yous tin utilisation BufferedReader or FileInputStream to read the content of an XML file every bit String past times using the techniques, I own got discussed inwards my before post service 3 ways to convert InputStream to String inwards Java. But this post service is almost a novel library called jcabi-xml which makes working amongst XML file actually easy. You tin parse the XML file using XPath expression, yous tin exercise XSL transformation, XSD schema validation in addition to yous tin fifty-fifty parse whole XML file every bit String inwards simply a span of lines of code.
I was playing amongst this novel XML library in addition to idea to percentage a span of examples of XML processing to demo how powerful it is. By the way, spell reading XML file every bit String i affair yous must yell back is graphic symbol encoding, which is specified inwards the header of an XML file.
If yous utilisation whatsoever XML library or fifty-fifty XML parser similar DOM in addition to SAX, yous don't demand to brand whatsoever additional adjustment, they volition own got attention of reading String wrong encoding, but if yous utilisation BufferedReader or whatsoever full general Stream reader, yous must ensure that right graphic symbol encoding is used.
In this article, yous volition acquire 3 ways to read XML file every bit String inwards Java, get-go past times using FileReader in addition to BufferedReader, instant past times using DOM parser in addition to tertiary past times using open-source XML library jcabi-xml.
BTW, if yous are novel to XML processing inwards Java, I likewise advise yous own got a await at Core Java Volume II - Advanced Features, ninth Edition by Cay S. Horstmann. It volition assistance yous to acquire in addition to empathize to a greater extent than advanced features of Java e.g. JDBC, XML, JMX, JMS etc.
The instant instance is almost DOM parser, which is peachy for reading minor XML files because it charge them solely into retention in addition to and then parse it past times creating a DOM tree. It's proficient for parsing huge XML file because that would require large retention in addition to nonetheless may halt upwards inwards java.lang.OutOfMemoryError : Java heap space. Interesting betoken is, toString() method of Document object volition non render String representation of XML, which way this is non suitable for the labor inwards manus but yous tin exercise a lot past times calling diverse methods of DOM API.
The tertiary instance is interesting, it uses an opened upwards origin library called jcabi-xml, which provides a convenient shape called XMLDocument to stand upwards for an XML file inwards memory. This shape has overridden the toString() method to render String representation of XML file itself. So yous tin read entire XML every bit String past times using simply 2 lines.
Here is our sample Java programme to demonstrate all 3 methods :
Output
XML to String using BufferedReader :
XML every bit String using DOM Parser :
[#document: null]
XML every bit String using JCabi library :
That's all almost how to read XML file every bit String inwards Java. You own got seen all 3 approaches to acquire XML every bit String in addition to yous tin compare them easily. BufferedReader doesn't own got XML encoding defined inwards the header, yous own got to specify it manually if yous desire to read an XML file encoded inwards a dissimilar graphic symbol encoding.
In our example, since nosotros utilisation FileReader, nosotros don't own got that option, but if yous demand to specify a dissimilar encoding in addition to then platform's default graphic symbol encoding in addition to then delight utilisation InputStreamReader. Also, when nosotros utilisation BufferedReader yous likewise demand to own got are of the novel line, which could live on dissimilar inwards dissimilar platform e.g. UNIX in addition to Windows uses dissimilar characters for the novel line.
DOM parser is the right way to parse XML files but unfortunately, its toString() doesn't render what yous want. Now if yous await at our 2 describe of piece of employment code using novel XML library jcabi-xml, its a breeze. That's why if yous tin utilisation opened upwards origin library, utilisation this one, it volition brand your XML parsing, validation, in addition to transformation easy.
Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services in addition to REST API amongst Spring Boot
example]Java guide to parse XML file using DOM parser? [example] Step past times Step guide to read XML using SAX parser inwards Java? [guide] How to lead XML chemical factor using XPath inwards Java? [solution] A divergence betwixt DOM in addition to SAX parser inwards XML? [answer] How to escape XML particular characters inwards Java String? [answer] How to marshall in addition to unmarshall Java to XML using JAXB? [example] XPath Tutorials for Beginner Java Developers [tutorial] How to procedure XML file using JDOM parser inwards Java? [example] How to evaluate XPath human face inwards Java? [example]
I was playing amongst this novel XML library in addition to idea to percentage a span of examples of XML processing to demo how powerful it is. By the way, spell reading XML file every bit String i affair yous must yell back is graphic symbol encoding, which is specified inwards the header of an XML file.
If yous utilisation whatsoever XML library or fifty-fifty XML parser similar DOM in addition to SAX, yous don't demand to brand whatsoever additional adjustment, they volition own got attention of reading String wrong encoding, but if yous utilisation BufferedReader or whatsoever full general Stream reader, yous must ensure that right graphic symbol encoding is used.
In this article, yous volition acquire 3 ways to read XML file every bit String inwards Java, get-go past times using FileReader in addition to BufferedReader, instant past times using DOM parser in addition to tertiary past times using open-source XML library jcabi-xml.
3 Ways to Read XML into String inwards Java
There are multiple ways to read in addition to procedure XML file in addition to generate String out of it in addition to nosotros volition meet 3 of them. Two of that approach are based on criterion classes in addition to interfaces from JDK itself in addition to 3rd approach volition brand utilisation of opened upwards origin library. For our instance purpose, nosotros volition read next XML file every bit String :<?xml version="1.0" encoding="UTF-8"?> <banks> <bank id="1"> <name>Barclays Bank</name> <headquarter>London</headquarter> </bank> <bank id="2"> <name>Goldman Sachs</name> <headquarter>NewYork</headquarter> </bank> <bank id="3"> <name>ICBC</name> <headquarter>Beijing</headquarter> </bank> </banks>
BTW, if yous are novel to XML processing inwards Java, I likewise advise yous own got a await at Core Java Volume II - Advanced Features, ninth Edition by Cay S. Horstmann. It volition assistance yous to acquire in addition to empathize to a greater extent than advanced features of Java e.g. JDBC, XML, JMX, JMS etc.
Java Program to read XML into String
Here is our Java programme to read XML every bit String. It contains 3 example, first, i uses BufferedReader in addition to reads XML similar a text file. It's non peachy because yous demand to specify graphic symbol encoding past times yourself spell XML parser tin read it straight from XML header. In this approach, yous tin cook XML string past times reading file describe of piece of employment past times line.The instant instance is almost DOM parser, which is peachy for reading minor XML files because it charge them solely into retention in addition to and then parse it past times creating a DOM tree. It's proficient for parsing huge XML file because that would require large retention in addition to nonetheless may halt upwards inwards java.lang.OutOfMemoryError : Java heap space. Interesting betoken is, toString() method of Document object volition non render String representation of XML, which way this is non suitable for the labor inwards manus but yous tin exercise a lot past times calling diverse methods of DOM API.
The tertiary instance is interesting, it uses an opened upwards origin library called jcabi-xml, which provides a convenient shape called XMLDocument to stand upwards for an XML file inwards memory. This shape has overridden the toString() method to render String representation of XML file itself. So yous tin read entire XML every bit String past times using simply 2 lines.
Here is our sample Java programme to demonstrate all 3 methods :
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; /** * Java Program to read XML every bit String using BufferedReader, DOM parser in addition to jCabi-xml
* opened upwards origin library. */ public class XmlAsStringInJava { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { // our XML file for this example File xmlFile = new File("info.xml"); // Let's acquire XML file every bit String using BufferedReader // FileReader uses platform's default graphic symbol encoding // if yous demand to specify a dissimilar encoding, utilisation InputStreamReader Reader fileReader = new FileReader(xmlFile); BufferedReader bufReader = new BufferedReader(fileReader); StringBuilder sb = new StringBuilder(); String describe of piece of employment = bufReader.readLine(); while( describe of piece of employment != null){ sb.append(line).append("\n"); describe of piece of employment = bufReader.readLine(); } String xml2String = sb.toString(); System.out.println("XML to String using BufferedReader : "); System.out.println(xml2String); bufReader.close(); // parsing XML file to acquire every bit String using DOM Parser DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); Document xmlDom = docBuilder.parse(xmlFile); String xmlAsString = xmlDom.toString(); // this volition non impress what yous want System.out.println("XML every bit String using DOM Parser : "); System.out.println(xmlAsString); // Reading XML every bit String using jCabi library XML xml = new XMLDocument(new File("info.xml")); String xmlString = xml.toString(); System.out.println("XML every bit String using JCabi library : " ); System.out.println(xmlString); } }
Output
XML to String using BufferedReader :
<?xml version="1.0" encoding="UTF-8"?> <banks> <bank id="1"> <name>Barclays Bank</name> <headquarter>London</headquarter> </bank> <bank id="2"> <name>Goldman Sachs</name> <headquarter>NewYork</headquarter> </bank> <bank id="3"> <name>ICBC</name> <headquarter>Beijing</headquarter> </bank> </banks>
XML every bit String using DOM Parser :
[#document: null]
XML every bit String using JCabi library :
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <banks> <bank id="1"> <name>Barclays Bank</name> <headquarter>London</headquarter> </bank> <bank id="2"> <name>Goldman Sachs</name> <headquarter>NewYork</headquarter> </bank> <bank id="3"> <name>ICBC</name> <headquarter>Beijing</headquarter> </bank> </banks>
That's all almost how to read XML file every bit String inwards Java. You own got seen all 3 approaches to acquire XML every bit String in addition to yous tin compare them easily. BufferedReader doesn't own got XML encoding defined inwards the header, yous own got to specify it manually if yous desire to read an XML file encoded inwards a dissimilar graphic symbol encoding.
In our example, since nosotros utilisation FileReader, nosotros don't own got that option, but if yous demand to specify a dissimilar encoding in addition to then platform's default graphic symbol encoding in addition to then delight utilisation InputStreamReader. Also, when nosotros utilisation BufferedReader yous likewise demand to own got are of the novel line, which could live on dissimilar inwards dissimilar platform e.g. UNIX in addition to Windows uses dissimilar characters for the novel line.
DOM parser is the right way to parse XML files but unfortunately, its toString() doesn't render what yous want. Now if yous await at our 2 describe of piece of employment code using novel XML library jcabi-xml, its a breeze. That's why if yous tin utilisation opened upwards origin library, utilisation this one, it volition brand your XML parsing, validation, in addition to transformation easy.
Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services in addition to REST API amongst Spring Boot
example]