How To Read Xml File Equally String Inwards Java? Three Examples
Suppose yous own got an XML file as well as yous but desire to read as well as display the whole file every bit String inward Java, may hold upwards for debugging purpose. If yous are wondering how to do that inward Java, good at that topographic point are many ways to read XML every bit String inward Java. You tin move do it inward 1 trouble if yous are fine alongside using an opened upwards origin library or yous tin move do it inward a twain of lines of code inward nitty-gritty Java every bit well. Since an XML file is too a file, yous tin move exercise BufferedReader or FileInputStream to read the content of an XML file every bit String yesteryear using the techniques, I own got discussed inward my before postal service 3 ways to convert InputStream to String inward Java. But this postal service is most a novel library called jcabi-xml which makes working alongside XML file actually easy. You tin move parse the XML file using XPath expression, yous tin move do XSL transformation, XSD schema validation as well as yous tin move fifty-fifty parse whole XML file every bit String inward but a twain of lines of code.
I was playing alongside this novel XML library as well as idea to percentage a twain of examples of XML processing to present how powerful it is. By the way, piece reading XML file every bit String 1 affair yous must think is grapheme encoding, which is specified inward the header of an XML file.
If yous exercise whatever XML library or fifty-fifty XML parser similar DOM as well as SAX, yous don't require to brand whatever additional adjustment, they volition accept aid of reading String wrong encoding, but if yous exercise BufferedReader or whatever full general Stream reader, yous must ensure that right grapheme encoding is used.
In this article, yous volition larn 3 ways to read XML file every bit String inward Java, offset yesteryear using FileReader as well as BufferedReader, 2nd yesteryear using DOM parser as well as 3rd yesteryear using open-source XML library jcabi-xml.
BTW, if yous are novel to XML processing inward Java, I too advise yous accept a expect at Core Java Volume II - Advanced Features, ninth Edition by Cay S. Horstmann. It volition help yous to larn as well as sympathise to a greater extent than advanced features of Java e.g. JDBC, XML, JMX, JMS etc.
The 2nd instance is most DOM parser, which is slap-up for reading minor XML files because it charge them alone into retention as well as and thence parse it yesteryear creating a DOM tree. It's practiced for parsing huge XML file because that would require large retention as well as notwithstanding may terminate upwards inward java.lang.OutOfMemoryError : Java heap space. Interesting signal is, toString() method of Document object volition non render String representation of XML, which way this is non suitable for the chore inward mitt but yous tin move do a lot yesteryear calling diverse methods of DOM API.
The 3rd instance is interesting, it uses an opened upwards origin library called jcabi-xml, which provides a convenient flat called XMLDocument to stand upwards for an XML file inward memory. This flat has overridden the toString() method to render String representation of XML file itself. So yous tin move read entire XML every bit String yesteryear using but ii lines.
Here is our sample Java plan 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 most how to read XML file every bit String inward Java. You own got seen all 3 approaches to acquire XML every bit String as well as yous tin move compare them easily. BufferedReader doesn't accept XML encoding defined inward the header, yous own got to specify it manually if yous desire to read an XML file encoded inward a unlike grapheme encoding.
In our example, since nosotros exercise FileReader, nosotros don't own got that option, but if yous require to specify a unlike encoding as well as thence platform's default grapheme encoding as well as thence delight exercise InputStreamReader. Also, when nosotros exercise BufferedReader yous too require to accept are of the novel line, which could hold upwards unlike inward unlike platform e.g. UNIX as well as Windows uses unlike 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 expect at our ii trouble code using novel XML library jcabi-xml, its a breeze. That's why if yous tin move exercise opened upwards origin library, exercise this one, it volition brand your XML parsing, validation, as well as transformation easy.
Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services as well as REST API alongside Spring Boot
example]Java remove to parse XML file using DOM parser? [example] Step yesteryear Step remove to read XML using SAX parser inward Java? [guide] How to choose XML chemical portion using XPath inward Java? [solution] A deviation betwixt DOM as well as SAX parser inward XML? [answer] How to escape XML exceptional characters inward Java String? [answer] How to marshall as well as unmarshall Java to XML using JAXB? [example] XPath Tutorials for Beginner Java Developers [tutorial] How to procedure XML file using JDOM parser inward Java? [example] How to evaluate XPath appear inward Java? [example]
I was playing alongside this novel XML library as well as idea to percentage a twain of examples of XML processing to present how powerful it is. By the way, piece reading XML file every bit String 1 affair yous must think is grapheme encoding, which is specified inward the header of an XML file.
If yous exercise whatever XML library or fifty-fifty XML parser similar DOM as well as SAX, yous don't require to brand whatever additional adjustment, they volition accept aid of reading String wrong encoding, but if yous exercise BufferedReader or whatever full general Stream reader, yous must ensure that right grapheme encoding is used.
In this article, yous volition larn 3 ways to read XML file every bit String inward Java, offset yesteryear using FileReader as well as BufferedReader, 2nd yesteryear using DOM parser as well as 3rd yesteryear using open-source XML library jcabi-xml.
3 Ways to Read XML into String inward Java
There are multiple ways to read as well as procedure XML file as well as generate String out of it as well as nosotros volition run across 3 of them. Two of that approach are based on measure classes as well as interfaces from JDK itself as well as 3rd approach volition brand exercise 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 inward Java, I too advise yous accept a expect at Core Java Volume II - Advanced Features, ninth Edition by Cay S. Horstmann. It volition help yous to larn as well as sympathise 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 plan to read XML every bit String. It contains 3 example, first, 1 uses BufferedReader as well as reads XML similar a text file. It's non slap-up because yous require to specify grapheme encoding yesteryear yourself piece XML parser tin move read it straight from XML header. In this approach, yous tin move develop XML string yesteryear reading file trouble yesteryear line.The 2nd instance is most DOM parser, which is slap-up for reading minor XML files because it charge them alone into retention as well as and thence parse it yesteryear creating a DOM tree. It's practiced for parsing huge XML file because that would require large retention as well as notwithstanding may terminate upwards inward java.lang.OutOfMemoryError : Java heap space. Interesting signal is, toString() method of Document object volition non render String representation of XML, which way this is non suitable for the chore inward mitt but yous tin move do a lot yesteryear calling diverse methods of DOM API.
The 3rd instance is interesting, it uses an opened upwards origin library called jcabi-xml, which provides a convenient flat called XMLDocument to stand upwards for an XML file inward memory. This flat has overridden the toString() method to render String representation of XML file itself. So yous tin move read entire XML every bit String yesteryear using but ii lines.
Here is our sample Java plan 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 as well as 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 grapheme encoding // if yous require to specify a unlike encoding, exercise InputStreamReader Reader fileReader = new FileReader(xmlFile); BufferedReader bufReader = new BufferedReader(fileReader); StringBuilder sb = new StringBuilder(); String trouble = bufReader.readLine(); while( trouble != null){ sb.append(line).append("\n"); trouble = 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 most how to read XML file every bit String inward Java. You own got seen all 3 approaches to acquire XML every bit String as well as yous tin move compare them easily. BufferedReader doesn't accept XML encoding defined inward the header, yous own got to specify it manually if yous desire to read an XML file encoded inward a unlike grapheme encoding.
In our example, since nosotros exercise FileReader, nosotros don't own got that option, but if yous require to specify a unlike encoding as well as thence platform's default grapheme encoding as well as thence delight exercise InputStreamReader. Also, when nosotros exercise BufferedReader yous too require to accept are of the novel line, which could hold upwards unlike inward unlike platform e.g. UNIX as well as Windows uses unlike 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 expect at our ii trouble code using novel XML library jcabi-xml, its a breeze. That's why if yous tin move exercise opened upwards origin library, exercise this one, it volition brand your XML parsing, validation, as well as transformation easy.
Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services as well as REST API alongside Spring Boot
example]
0 Response to "How To Read Xml File Equally String Inwards Java? Three Examples"
Post a Comment