How To Read Xml File Equally String Inwards Java? Three Examples

Suppose yous own got an XML file together with yous simply desire to read together with display the whole file equally String inwards Java, may hold out for debugging purpose. If yous are wondering how to exercise that inwards Java, good at that spot are many ways to read XML equally String inwards Java. You tin exercise it inwards 1 trouble if yous are fine alongside using an opened upward rootage library or yous tin exercise it inwards a duo of lines of code inwards pith Java equally well. Since an XML file is likewise a file, yous tin usage BufferedReader or FileInputStream to read the content of an XML file equally String yesteryear 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 alongside XML file actually easy. You tin parse the XML file using XPath expression, yous tin exercise XSL transformation, XSD schema validation together with yous tin fifty-fifty parse whole XML file equally String inwards simply a duo of lines of code.

I was playing alongside this novel XML library together with idea to portion a duo of examples of XML processing to exhibit how powerful it is. By the way, piece reading XML file equally String 1 affair yous must yell upward is grapheme encoding, which is specified inwards the header of an XML file.

If yous usage whatever XML library or fifty-fifty XML parser similar DOM together with SAX, yous don't involve to brand whatever additional adjustment, they volition own got attention of reading String wrong encoding, but if yous usage BufferedReader or whatever full general Stream reader, yous must ensure that right grapheme encoding is used.

In this article, yous volition acquire 3 ways to read XML file equally String inwards Java, start yesteryear using FileReader together with BufferedReader, minute yesteryear using DOM parser together with 3rd yesteryear using open-source XML library jcabi-xml.




3 Ways to Read XML into String inwards Java

There are multiple ways to read together with procedure XML file together with generate String out of it together with nosotros volition encounter 3 of them. Two of that approach are based on measure classes together with interfaces from JDK itself together with 3rd approach volition brand usage of opened upward rootage library. For our instance purpose, nosotros volition read next XML file equally 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 propose yous own got a expect at Core Java Volume II - Advanced Features, ninth Edition  by Cay S. Horstmann. It volition assistance yous to acquire together with 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 equally String. It contains 3 example, first, 1 uses BufferedReader together with reads XML similar a text file. It's non peachy because yous involve to specify grapheme encoding yesteryear yourself piece XML parser tin read it straight from XML header. In this approach, yous tin gear upward XML string yesteryear reading file trouble yesteryear line.

The minute instance is almost DOM parser, which is peachy for reading modest XML files because it charge them only into retention together with and therefore parse it yesteryear creating a DOM tree. It's expert for parsing huge XML file because that would require large retention together with even therefore may goal upward inwards java.lang.OutOfMemoryError : Java heap space.  Interesting betoken is, toString() method of Document object volition non render String representation of XML, which agency this is non suitable for the chore inwards mitt but yous tin exercise a lot yesteryear calling diverse methods of DOM API.

The 3rd instance is interesting, it uses an opened upward rootage library called jcabi-xml, which provides a convenient degree called XMLDocument to stand upward for an XML file inwards memory. This degree has overridden the toString() method to render String representation of XML file itself. So yous tin read entire XML equally String yesteryear using simply 2 lines.

 Suppose yous own got an XML file together with yous simply desire to read together with display the whole file equally Stri How to Read XML File equally String inwards Java? 3 Examples


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 equally String using BufferedReader, DOM parser together with jCabi-xml 
  * opened upward rootage 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 equally String using BufferedReader         // FileReader uses platform's default grapheme encoding         // if yous involve to specify a unlike encoding, usage 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 equally 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 equally String using DOM Parser : ");         System.out.println(xmlAsString);                           // Reading XML equally String using jCabi library         XML xml = new XMLDocument(new File("info.xml"));         String xmlString = xml.toString();                 System.out.println("XML equally 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 equally String using DOM Parser :
[#document: null]

XML equally 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 equally String inwards Java. You own got seen all 3 approaches to acquire XML equally String together with 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 unlike grapheme encoding.


In our example, since nosotros usage FileReader, nosotros don't own got that option, but if yous involve to specify a unlike encoding together with therefore platform's default grapheme encoding together with therefore delight usage InputStreamReader. Also, when nosotros usage BufferedReader yous likewise involve to own got are of the novel line, which could hold out unlike inwards unlike platform e.g. UNIX together with 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 2 trouble code using novel XML library jcabi-xml, its a breeze. That's why if yous tin usage opened upward rootage library, usage this one, it volition brand your XML parsing, validation, together with transformation easy.


Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services together with REST API alongside Spring Boot
example]
  • Java take away to parse XML file using DOM parser? [example]
  • Step yesteryear Step take away to read XML using SAX parser inwards Java? [guide]
  • How to choose XML chemical constituent using XPath inwards Java? [solution]
  • A departure betwixt DOM together with SAX parser inwards XML? [answer]
  • How to escape XML exceptional characters inwards Java String? [answer]
  • How to marshall together with 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]



  • Komentar

    Postingan populer dari blog ini

    2 Ways To Banking Concern Tally If A String Is Rotation Of Other Inward Java?

    How To Convert String To Integer To String Inward Coffee Amongst Example

    How To Induce Chrome, Firefox Blurry, Over Bright, Fading Afterwards Windows Ten Update