Java xml file to source

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

Suppose you have an XML file and you just want to read and display the whole file as String in Java, may be for debugging purposes. If you are wondering how to do that in Java, well there are many ways to read XML as String in Java. You can do it in one line if you are fine with using an open-source library or you can do it in a couple of lines of code in core Java as well. Since an XML file is also a file, you can use BufferedReader or FileInputStream to read the content of an XML file as String by using the techniques, I have discussed in my earlier post 3 ways to convert InputStream to String in Java.

But this post is about a new library called jcabi-xml which makes working with XML file really easy. You can parse the XML file using XPath expression, you can do XSL transformation, XSD schema validation and you can even parse whole XML file as String in just a couple of lines of code.

I was playing with this new XML library and thought to share a couple of examples of XML processing to show how powerful it is. By the way, while reading the XML file as String one thing you must remember is character encoding, which is specified in the header of an XML file.

Читайте также:  Только буквы и цифры html

If you use any XML library or even XML parser like DOM and SAX, you don’t need to make any additional adjustment, they will take care of reading String incorrect encoding, but if you use BufferedReader or any general Stream reader, you must ensure that correct character encoding is used.

In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.

3 Ways to Read XML into String in Java

There are multiple ways to read and process XML files and generate String out of it and we will see three of them. Two of those approaches are based on standard classes and interfaces from JDK itself and 3rd approach will make use of an open-source library. For our example purpose, we will read the following XML file as 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 are new to XML processing in Java, I also suggest you take a look at Core Java Volume II — Advanced Features, 9th Edition by Cay S. Horstmann. It will help you to learn and understand more advanced features of Java e.g. JDBC, XML, JMX, JMS, etc.

Java Program to read XML into String

Here is our Java program to read XML as String. It contains three examples, first, one uses BufferedReader and reads XML like a text file. It’s not great because you need to specify character encoding by yourself while the XML parser can read it directly from XML header. In this approach, you can build XML string by reading file line by line.

Читайте также:  background-repeat

The second example is about the DOM parser, which is great for reading small XML files because it load them entirely into memory and then parse it by creating a DOM tree. It’s good for parsing huge XML file because that would require large memory and still may end up in java.lang.OutOfMemoryError : Java heap space.

An interesting point is, toString() method of Document object will not return String representation of XML, which means this is not suitable for the job in hand but you can do a lot by calling various methods of DOM API.

The third example is interesting, it uses an open source library called jcabi-xml, which provides a convenient class called XMLDocument to represent an XML file in memory. This class has overridden the toString() method to return String representation of XML file itself. So you can read entire XML as String by using just two lines.

How to read XML as String in Java 3 Example

Here is our sample Java program to demonstrate all three 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 as String using BufferedReader, * DOM parser and jCabi-xml 
 * open source 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 get XML file as String using BufferedReader // FileReader uses platform's default character encoding // if you need to specify a different encoding, // use InputStreamReader Reader fileReader = new FileReader(xmlFile); BufferedReader bufReader = new BufferedReader(fileReader); StringBuilder sb = new StringBuilder(); String line = bufReader.readLine(); while( line != null)< sb.append(line).append("\n"); line = bufReader.readLine(); > String xml2String = sb.toString(); System.out.println("XML to String using BufferedReader : "); System.out.println(xml2String); bufReader.close(); // parsing XML file to get as String using DOM Parser DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); Document xmlDom = docBuilder.parse(xmlFile); String xmlAsString = xmlDom.toString(); // this will not print what you want System.out.println("XML as String using DOM Parser : "); System.out.println(xmlAsString); // Reading XML as String using jCabi library XML xml = new XMLDocument(new File("info.xml")); String xmlString = xml.toString(); System.out.println("XML as 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 as String using DOM Parser :
[#document: null]

XML as 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 about how to read XML file as String in Java. You have seen all three approaches to get XML as String and you can compare them easily. BufferedReader doesn’t take XML encoding defined in the header, you have to specify it manually if you want to read an XML file encoded in a different character encoding.

In our example, since we use FileReader, we don’t have that option, but if you need to specify a different encoding the platform’s default character encoding then please use InputStreamReader . Also, when we use BufferedReader you also need to take are of the new line, which could be different in different platform e.g. UNIX and Windows uses different characters for the new line.

DOM parser is the right way to parse XML files but unfortunately, its toString() doesn’t return what you want. Now if you look at our two line code using new XML library jcabi-xml, its a breeze. That’s why if you can use the open-source library, use this one, it will make your XML parsing, validation, and transformation easy.

  • How to convert Java object to XML document using JAXB? [example]
  • Java guide to parse XML file using DOM parser? [example]
  • Step by Step guide to read XML using SAX parser in Java? [guide]
  • How to select XML element using XPath in Java? [solution]
  • A difference between DOM and SAX parser in XML? [answer]
  • How to escape XML special characters in Java String? [answer]
  • How to marshall and unmarshall Java to XML using JAXB? [example]
  • XPath Tutorials for Beginner Java Developers [tutorial]
  • How to process XML file using JDOM parser in Java? [example]
  • How to evaluate XPath expression in Java? [example]

Источник

Java Guides

JDOM is an open source, Java-based library to parse XML documents. It is typically a Java developer-friendly API. It is Java optimized and it uses Java collections like List and Arrays.

JDOM works with DOM and SAX APIs and combines the best of the two. It is of low memory footprint and is nearly as fast as SAX.

JDOM Dependency

JDOM is not part of standard JDK, so to work with JDOM you will need to download its binaries from JDOM Official Website. Once binaries are downloaded, include JDOM jar in your project classpath and you are good to start using it. For this example, we will use current JDOM version 2.0.6 (jdom-2.0.6.jar). If you are working with a maven based project then add below maven dependency to your pom.xml.

 https://mvnrepository.com/artifact/org.jdom/jdom2 --> dependency> groupId>org.jdomgroupId> artifactId>jdom2artifactId> version>2.0.6version> dependency>

JDOM Parser Important Classes

  1. org.jdom2.input.DOMBuilder: Uses DOM Parser to parse the XML and transform it to JDOM Document.
  2. org.jdom2.input.SAXBuilder: Uses SAX Parser to parse the XML and transform it to JDOM Document.
  3. org.jdom2.input.StAXEventBuilder: Uses STAX Event Parser to parse the XML and transform it to JDOM Document.
  4. org.jdom2.input.StAXStreamBuilder: Uses STAX Stream Parser to parse the XML and transform it to JDOM Document.
  5. org.jdom2.Document: JDOM Document provides useful methods to get root element, read, edit and write content to Elements. Here we will use it to get the root element from XML.
  6. org.jdom2.Element: Provides useful methods to get list of child elements, get child element value, get attribute values.

Program Development Steps

  1. Input jdom_users.xml File(XML file we will read)
  2. Create User class (populate XML data into User object)
  3. Program to Read XML File in Java using Java JDOM Parser

1. Input jdom_users.xml File(XML file we will read)

Make sure that you have a jdom_users.xml file in a file system and add the below contents to this file:

xml version="1.0" encoding="UTF-8"?> Users> User id= "1"> firstName>RameshfirstName> lastName>FadatarelastName> age>28age> gender>Malegender> User> User id= "2"> firstName>JohnfirstName> lastName>CenalastName> age>45age> gender>Malegender> User> User id= "3"> firstName>TomfirstName> lastName>CruiselastName> age>40age> gender>Malegender> User> Users>

2. Create User class (populate XML data into User object)

package net.javaguides.javaxmlparser.jdom; public class User < private int id; private String firstName; private String lastName; private int age; private String gender; public int getId() < return id; > public void setId(int i) < this.id = i; > public String getFirstName() < return firstName; > public void setFirstName(String firstName) < this.firstName = firstName; > public String getLastName() < return lastName; > public void setLastName(String lastName) < this.lastName = lastName; > public int getAge() < return age; > public void setAge(int age) < this.age = age; > public String getGender() < return gender; > public void setGender(String gender) < this.gender = gender; > @Override public String toString() < return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" + gender + "]"; > >

3. Program to Read XML File in Java using Java JDOM Parser

package net.javaguides.javaxmlparser.jdom; import java.io.File; import java.util.ArrayList; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; public class ReadXMLFile < public static void main(String[] args) < final String fileName = "jdom_users.xml"; try < // we can create JDOM Document from DOM, SAX and STAX Parser Builder classes SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(fileName); Document jdomDoc = (Document) builder.build(xmlFile); Element root = jdomDoc.getRootElement(); List  Element > listOfUsers = root.getChildren("User"); List  User > userList = new ArrayList < >(); for (Element userElement: listOfUsers) < User user = new User(); user.setId(Integer.parseInt(userElement.getAttributeValue("id"))); user.setAge(Integer.parseInt(userElement.getChildText("age"))); user.setFirstName(userElement.getChildText("firstName")); user.setLastName(userElement.getChildText("lastName")); user.setGender(userElement.getChildText("gender")); userList.add(user); > // lets print Users list information userList.forEach(user - > < System.out.println(user.toString()); >); > catch (Exception e) < e.printStackTrace(); > > >
User [id=1, firstName=Ramesh, lastName=Fadatare, age=28, gender=Male] User [id=2, firstName=John, lastName=Cena, age=45, gender=Male] User [id=3, firstName=Tom, lastName=Cruise, age=40, gender=Male]

Источник

Оцените статью