How To Read Xml File Equally String Inward Java? Iii Examples

Suppose you lot possess got an XML file too you lot simply desire to read too display the whole file every bit String inwards Java, may move for debugging purpose. If you lot are wondering how to practise that inwards Java, good at that spot are many ways to read XML every bit String inwards Java. You tin flaming practise it inwards ane business if you lot are fine amongst using an opened upward rootage library or you lot tin flaming practise it inwards a yoke of lines of code inwards meat Java every bit well. Since an XML file is likewise a file, you lot tin flaming utilisation BufferedReader or FileInputStream to read the content of an XML file every bit String yesteryear using the techniques, I possess got discussed inwards my before postal service 3 ways to convert InputStream to String inwards Java. But this postal service is almost a novel library called jcabi-xml which makes working amongst XML file actually easy. You tin flaming parse the XML file using XPath expression, you lot tin flaming practise XSL transformation, XSD schema validation too you lot tin flaming fifty-fifty parse whole XML file every bit String inwards simply a yoke of lines of code.

I was playing amongst this novel XML library too idea to portion a yoke of examples of XML processing to demo how powerful it is. By the way, field reading XML file every bit String ane affair you lot must recall is grapheme encoding, which is specified inwards the header of an XML file.

If you lot utilisation whatever XML library or fifty-fifty XML parser similar DOM too SAX, you lot don't demand to brand whatever additional adjustment, they volition possess got attention of reading String wrong encoding, but if you lot utilisation BufferedReader or whatever full general Stream reader, you lot must ensure that right grapheme encoding is used.

In this article, you lot volition acquire 3 ways to read XML file every bit String inwards Java, showtime yesteryear using FileReader too BufferedReader, minute yesteryear using DOM parser too 3rd yesteryear using open-source XML library jcabi-xml.




3 Ways to Read XML into String inwards Java

There are multiple ways to read too procedure XML file too generate String out of it too nosotros volition come across 3 of them. Two of that approach are based on criterion classes too interfaces from JDK itself too 3rd approach volition brand utilisation of opened upward rootage 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 you lot are novel to XML processing inwards Java, I likewise advise you lot possess got a await at Core Java Volume II - Advanced Features, ninth Edition  by Cay S. Horstmann. It volition help you lot to acquire too 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 programme to read XML every bit String. It contains 3 example, first, ane uses BufferedReader too reads XML similar a text file. It's non corking because you lot demand to specify grapheme encoding yesteryear yourself field XML parser tin flaming read it straight from XML header. In this approach, you lot tin flaming educate XML string yesteryear reading file business yesteryear line.

The minute instance is almost DOM parser, which is corking for reading modest XML files because it charge them exclusively into retentivity too and then parse it yesteryear creating a DOM tree. It's proficient for parsing huge XML file because that would require large retentivity too even thence may terminate upward inwards java.lang.OutOfMemoryError : Java heap space.  Interesting hollo for is, toString() method of Document object volition non render String representation of XML, which agency this is non suitable for the project inwards paw but you lot tin flaming practise 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 shape called XMLDocument to stand upward for an XML file inwards memory. This shape has overridden the toString() method to render String representation of XML file itself. So you lot tin flaming read entire XML every bit String yesteryear using simply 2 lines.

 Suppose you lot possess got an XML file too you lot simply desire to read too display the whole file every bit Stri How to Read XML File every bit 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 every bit String using BufferedReader, DOM parser too 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 every bit String using BufferedReader         // FileReader uses platform's default grapheme encoding         // if you lot demand to specify a unlike encoding, utilisation InputStreamReader         Reader fileReader = new FileReader(xmlFile);         BufferedReader bufReader = new BufferedReader(fileReader);                  StringBuilder sb = new StringBuilder();         String business = bufReader.readLine();         while( business != null){             sb.append(line).append("\n");             business = 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 you lot 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 possess got seen all 3 approaches to acquire XML every bit String too you lot tin flaming compare them easily. BufferedReader doesn't possess got XML encoding defined inwards the header, you lot possess got to specify it manually if you lot desire to read an XML file encoded inwards a unlike grapheme encoding.


In our example, since nosotros utilisation FileReader, nosotros don't possess got that option, but if you lot demand to specify a unlike encoding too then platform's default grapheme encoding too then delight utilisation InputStreamReader. Also, when nosotros utilisation BufferedReader you lot likewise demand to possess got are of the novel line, which could move unlike inwards unlike platform e.g. UNIX too 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 you lot want. Now if you lot await at our 2 business code using novel XML library jcabi-xml, its a breeze. That's why if you lot tin flaming utilisation opened upward rootage library, utilisation this one, it volition brand your XML parsing, validation, too transformation easy.


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



  • Belum ada Komentar untuk "How To Read Xml File Equally String Inward Java? Iii Examples"

    Posting Komentar

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel