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

Suppose yous conduct maintain an XML file as well as yous but desire to read as well as display the whole file equally String inwards Java, may move for debugging purpose. If yous are wondering how to practice that inwards Java, good in that place are many ways to read XML equally String inwards Java. You tin flaming practice it inwards 1 describe of piece of employment if yous are fine amongst using an opened upward root library or yous tin flaming practice it inwards a distich of lines of code inwards nub Java equally well. Since an XML file is equally good a file, yous tin flaming utilisation BufferedReader or FileInputStream to read the content of an XML file equally String yesteryear using the techniques, I conduct maintain discussed inwards my before shipping 3 ways to convert InputStream to String inwards Java. But this shipping is close a novel library called jcabi-xml which makes working amongst XML file actually easy. You tin flaming parse the XML file using XPath expression, yous tin flaming practice XSL transformation, XSD schema validation as well as yous tin flaming fifty-fifty parse whole XML file equally String inwards but a distich of lines of code.

I was playing amongst this novel XML library as well as idea to part a distich of examples of XML processing to present how powerful it is. By the way, spell reading XML file equally String 1 affair yous must cry upward is graphic symbol encoding, which is specified inwards the header of an XML file.

If yous utilisation whatever XML library or fifty-fifty XML parser similar DOM as well as SAX, yous don't involve to brand whatever additional adjustment, they volition conduct maintain tending of reading String wrong encoding, but if yous utilisation BufferedReader or whatever 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 equally String inwards Java, kickoff yesteryear using FileReader as well as BufferedReader, instant yesteryear using DOM parser as well as 3rd yesteryear using open-source XML library jcabi-xml.




3 Ways to Read XML into String inwards 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 come across 3 of them. Two of that approach are based on criterion classes as well as interfaces from JDK itself as well as 3rd approach volition brand utilisation of opened upward root 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 equally good propose yous conduct maintain a expect at Core Java Volume II - Advanced Features, ninth Edition  by Cay S. Horstmann. It volition help yous to acquire as well as 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 as well as reads XML similar a text file. It's non dandy because yous involve to specify graphic symbol encoding yesteryear yourself spell XML parser tin flaming read it direct from XML header. In this approach, yous tin flaming railroad train XML string yesteryear reading file describe of piece of employment yesteryear line.

The instant instance is close DOM parser, which is dandy for reading minor XML files because it charge them solely into retentiveness as well as hence parse it yesteryear creating a DOM tree. It's skilful for parsing huge XML file because that would require large retentiveness as well as all the same may terminate upward inwards java.lang.OutOfMemoryError : Java heap space.  Interesting cry for is, toString() method of Document object volition non render String representation of XML, which way this is non suitable for the chore inwards manus but yous tin flaming practice a lot yesteryear calling diverse methods of DOM API.

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

 Suppose yous conduct maintain an XML file as well as yous but desire to read as well as 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 as well as jCabi-xml 
  * opened upward root 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 graphic symbol encoding         // if yous involve to specify a unlike 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 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 close how to read XML file equally String inwards Java. You conduct maintain seen all 3 approaches to acquire XML equally String as well as yous tin flaming compare them easily. BufferedReader doesn't conduct maintain XML encoding defined inwards the header, yous conduct maintain to specify it manually if yous desire to read an XML file encoded inwards a unlike graphic symbol encoding.


In our example, since nosotros utilisation FileReader, nosotros don't conduct maintain that option, but if yous involve to specify a unlike encoding hence platform's default graphic symbol encoding hence delight utilisation InputStreamReader. Also, when nosotros utilisation BufferedReader yous equally good involve to conduct maintain are of the novel line, which could move unlike inwards 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 describe of piece of employment code using novel XML library jcabi-xml, its a breeze. That's why if yous tin flaming utilisation opened upward root library, utilisation 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 amongst Spring Boot
example]
  • Java guide to parse XML file using DOM parser? [example]
  • Step yesteryear Step guide to read XML using SAX parser inwards Java? [guide]
  • How to choose XML chemical ingredient using XPath inwards Java? [solution]
  • A departure betwixt DOM as well as SAX parser inwards XML? [answer]
  • How to escape XML particular characters inwards 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 inwards Java? [example]
  • How to evaluate XPath seem inwards Java? [example]




  • Sumber https://javarevisited.blogspot.com/

    0 Response to "How To Read Xml File Equally String Inwards Java? Three Examples"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel