Tuesday, May 7, 2024
HomeJavaMethods to Learn XML File as String in Java? 3 Examples

Methods to Learn XML File as String in Java? 3 Examples


Suppose you’ve gotten an XML file and also you simply need to learn and show the entire file as String in Java, could also be for debugging functions. In case you are questioning how to try this in Java, effectively there are a lot of methods to learn XML as String in Java. You are able to do it in a single line if you’re wonderful with utilizing an open-source library or you are able to do it in a few traces of code in core Java as effectively. Since an XML file can also be a file, you should utilize BufferedReader or FileInputStream to learn the content material of an XML file as String by utilizing the strategies, I’ve mentioned in my earlier publish 3 methods to transform InputStream to String in Java
However this publish is a few new library referred to as jcabi-xml which makes working with XML file very easy. You possibly can parse the XML file utilizing XPath expression, you are able to do XSL transformation, XSD schema validation and you may even parse complete XML file as String in simply a few traces of code.

I used to be enjoying with this new XML library and thought to share a few examples of XML processing to point out how highly effective it’s. By the way in which, whereas studying the XML file as String one factor you need to bear in mind is character encoding, which is specified within the header of an XML file.

In the event you use any XML library and even XML parser like DOM and SAX, you needn’t make any extra adjustment, they are going to maintain studying String incorrect encoding, however for those who use BufferedReader or any common Stream reader, you need to be certain that appropriate character encoding is used.

On this article, you’ll be taught 3 ways to learn XML recordsdata as String in Java, first by utilizing FileReader and BufferedReader, second by utilizing DOM parser, and third by utilizing open-source XML library jcabi-xml.

3 Methods to Learn XML into String in Java

There are a number of methods to learn and course of XML recordsdata and generate String out of it and we’ll see three of them. Two of these approaches are based mostly on commonplace courses and interfaces from JDK itself and third method will make use of an open-source library. For our instance goal, we’ll learn the next XML file as String :

<?xml model="1.0" encoding="UTF-8"?>
<banks>
    <financial institution id="1">
        <identify>Barclays Financial institution</identify>
        <headquarter>London</headquarter>
    </financial institution>
    <financial institution id="2">
        <identify>Goldman Sachs</identify>
        <headquarter>NewYork</headquarter>
    </financial institution>
    <financial institution id="3">
        <identify>ICBC</identify>
        <headquarter>Beijing</headquarter>
    </financial institution>
</banks>

BTW, if you’re new to XML processing in Java, I additionally counsel you check out Core Java Quantity II – Superior Options, ninth Version by Cay S. Horstmann. It can allow you to to be taught and perceive extra superior options of Java e.g. JDBC, XML, JMX, JMS, and so on.

How to Read XML File as String in Java? 3 Examples

Java Program to learn XML into String

Right here is our Java program to learn XML as String. It incorporates three examples, first, one makes use of BufferedReader and reads XML like a textual content file. It is not nice as a result of that you must specify character encoding by your self whereas the XML parser can learn it immediately from XML header. On this method, you may construct XML string by studying file line by line.

The second instance is concerning the DOM parser, which is nice for studying small XML recordsdata as a result of it load them completely into reminiscence after which parse it by making a DOM tree. It is good for parsing large XML file as a result of that will require giant reminiscence and nonetheless might find yourself in java.lang.OutOfMemoryError : Java heap area.  

An fascinating level is, toString() technique of Doc object is not going to return String illustration of XML, which suggests this isn’t appropriate for the job in hand however you are able to do so much by calling numerous strategies of DOM API.

The third instance is fascinating, it makes use of an open supply library referred to as jcabi-xml, which gives a handy class referred to as XMLDocument to characterize an XML file in reminiscence. This class has overridden the toString() technique to return String illustration of XML file itself. So you may learn total XML as String by utilizing simply two traces.

How to read XML as String in Java 3 Example

Right here is our pattern Java program to reveal all three strategies :

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.Doc;
import org.xml.sax.SAXException;

import com.jcabi.xml.XML;
import com.jcabi.xml.XMLDocument;


/**
  * Java Program to learn XML as String utilizing BufferedReader,
  *  DOM parser and jCabi-xml 
  * open supply library.
  */
public class XmlAsStringInJava {

    public static void important(String[] args) 
          throws ParserConfigurationException, SAXException, IOException {
        
        // our XML file for this instance
        File xmlFile = new File("information.xml");
        
        // Let's get XML file as String utilizing BufferedReader
        // FileReader makes use of platform's default character encoding
        // if that you must specify a unique encoding, 
        // use InputStreamReader
        Reader fileReader = new FileReader(xmlFile);
        BufferedReader bufReader = new BufferedReader(fileReader);
        
        StringBuilder sb = new StringBuilder();
        String line = bufReader.readLine();
        whereas( line != null){
            sb.append(line).append("n");
            line = bufReader.readLine();
        }
        String xml2String = sb.toString();
        System.out.println("XML to String utilizing BufferedReader : ");
        System.out.println(xml2String);
        
        bufReader.shut();
       
        // parsing XML file to get as String utilizing DOM Parser
        DocumentBuilderFactory dbFactory 
             = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        Doc xmlDom = docBuilder.parse(xmlFile);
        
        String xmlAsString = xmlDom.toString(); 
        // this is not going to print what you need
        System.out.println("XML as String utilizing DOM Parser : ");
        System.out.println(xmlAsString);
        
        
        // Studying XML as String utilizing jCabi library
        XML xml = new XMLDocument(new File("information.xml"));
        String xmlString = xml.toString();        
        System.out.println("XML as String utilizing JCabi library : " );
        System.out.println(xmlString);
      }
}

Output
XML to String utilizing BufferedReader :

<?xml model="1.0" encoding="UTF-8"?>
<banks>
    <financial institution id="1">
        <identify>Barclays Financial institution</identify>
        <headquarter>London</headquarter>
    </financial institution>
    <financial institution id="2">
        <identify>Goldman Sachs</identify>
        <headquarter>NewYork</headquarter>
    </financial institution>
    <financial institution id="3">
        <identify>ICBC</identify>
        <headquarter>Beijing</headquarter>
    </financial institution>
</banks>

XML as String utilizing DOM Parser :
[#document: null]

XML as String utilizing JCabi library :

<?xml model="1.0" encoding="UTF-8" standalone="no"?>
<banks>
    <financial institution id="1">
        <identify>Barclays Financial institution</identify>
        <headquarter>London</headquarter>
    </financial institution>
    <financial institution id="2">
        <identify>Goldman Sachs</identify>
        <headquarter>NewYork</headquarter>
    </financial institution>
    <financial institution id="3">
        <identify>ICBC</identify>
        <headquarter>Beijing</headquarter>
    </financial institution>
</banks>

That is all about methods to learn XML file as String in Java. You have got seen all three approaches to get XML as String and you may evaluate them simply. BufferedReader does not take XML encoding outlined within the header, it’s important to specify it manually if you wish to learn an XML file encoded in a unique character encoding.

In our instance, since we use FileReader, we do not have that possibility, but when that you must specify a unique encoding the platform’s default character encoding then please use InputStreamReader. Additionally, once we use BufferedReader you additionally have to take are of the brand new line, which may very well be totally different in numerous platform e.g. UNIX and Home windows makes use of totally different characters for the brand new line.

DOM parser is the suitable technique to parse XML recordsdata however sadly, its toString() does not return what you need. Now for those who have a look at our two line code utilizing new XML library jcabi-xml, its a breeze. That is why if you should utilize the open-source library, use this one, it can make your XML parsing, validation, and transformation straightforward.

In the event you like this Java XML tutorial and have an interest to be taught extra about XML processing in Java, you may as well take a look at the next tutorials :

  • Methods to convert Java object to XML doc utilizing JAXB? [example]
  • Java information to parse XML file utilizing DOM parser? [example]
  • Step by Step information to learn XML utilizing SAX parser in Java? [guide]
  • Methods to choose XML component utilizing XPath in Java? [solution]
  • A distinction between DOM and SAX parser in XML? [answer]
  • Methods to escape XML particular characters in Java String? [answer]
  • Methods to marshall and unmarshall Java to XML utilizing JAXB? [example]
  • XPath Tutorials for Newbie Java Builders [tutorial]
  • Methods to course of XML file utilizing JDOM parser in Java? [example]
  • Methods to consider XPath expression in Java? [example]



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments