Header Ads Widget

Responsive Advertisement

how to convert xml to String in java code


Code:

java

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.io.StringWriter;

 

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

 

public class XmlAsStringInJava {

 

    public static void main(String args[]) {

        String data = convertXMLFileToString("C:\\Users\\kmandal\\Desktop\\xmlData.xml");

        if (data != null) {

            System.out.println(data);

        }

    }

 

    public static String convertXMLFileToString(String fileName) {

        try {

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

            InputStream inputStream = new FileInputStream(new File(fileName));

            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);

           

            StringWriter stw = new StringWriter();

            Transformer serializer = TransformerFactory.newInstance().newTransformer();

           

            // Enable pretty printing

            serializer.setOutputProperty(OutputKeys.INDENT, "yes");

            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

           

            serializer.transform(new DOMSource(doc), new StreamResult(stw));

            return stw.toString();

        } catch (Exception e) {

            System.err.println("Error occurred while converting XML to String: " + e.getMessage());

            e.printStackTrace();

        }

        return null;

    }

}

 

The code provided reads an XML file from the file system and converts it into a String for further manipulation or display. It uses the DocumentBuilderFactory to parse the XML file and Transformer to convert the DOM (Document Object Model) into a string.

How the Code Works:

  1. convertXMLFileToString Method:
    • The method takes the XML file's path (fileName) as input and returns the content of the XML file as a string.
    • It uses DocumentBuilderFactory to parse the file into a Document object.
    • The Transformer class is then used to convert the Document object back into a string format (stw.toString()).
  2. main Method:
    • The main method calls convertXMLFileToString, passing the path of the XML file (xmlData.xml), and prints the XML content as a string.

Usage Example:

For an XML file stored at "C:\\Users\\kmandal\\Desktop\\xmlData.xml", the code will convert the content of that file into a string and print it to the console.

 

Key Enhancements:

  1. Indentation: The output XML will now be properly indented (4 spaces by default) for better readability.
  2. Error Handling: If an error occurs, it will print a message to the console, making it easier to understand what went wrong.

Example Output:

With an XML file, the output might look like this:

xml

<?xml version="1.0" encoding="UTF-8"?>

<Data>

 <user>

   <userId>12222</userId>

   <loginName>Kartik</loginName>

   <fullName> Kartik Chandra Mandal</fullName>

  <userProfileList>

   <parameter>

    <key>df</key>

    <value>etry</value>

   </parameter>

  </userProfileList>

 </user>

 <metaData>

  <defaultCurrencyCode>INR</defaultCurrencyCode>

  <year>25-02-2020</year>

  <month>12</month>

  <weekOfMonth>3rd</weekOfMonth>

  <startDate>25-02-2020</startDate>

  <endDate>25-02-2020</endDate>

 </metaData>

 <groups>

  <locale>EN</locale>

  <dateFormat>25-02-2020</dateFormat>

  <currencySymbol>USD</currencySymbol>

  <cobrandId>99</cobrandId>

  <userCurrency>USD</userCurrency>

  <decimalSeparator>Yes</decimalSeparator>

  <groupingSeparator>YES</groupingSeparator>

  <groupPattern>YES</groupPattern>

  <group>

   <categories>

    <category>

     <type>GOAL</type>

     <categoryId>KK</categoryId>

     <currencyCode>USD</currencyCode>

     <name>Kartik</name>

     <goal>Car</goal>

     <threshold>123</threshold>

     <thresholdAmount>123</thresholdAmount>

     <current>1223</current>

     <average>123</average>

    </category>

   </categories>

   <totalGoal>5</totalGoal>

   <totalAmount>43645</totalAmount>

   <categoryTypes>

    <categoryType>

     <categoryTypeId></categoryTypeId>

     <categoryTypeName></categoryTypeName>

     <categories>

      <category>

       <type>GOAL</type>

       <categoryId>KK</categoryId>

       <currencyCode>USD</currencyCode>

       <name>Kartik</name>

       <goal>Car</goal>

       <threshold>123</threshold>

       <thresholdAmount>123</thresholdAmount>

       <current>1223</current>

       <average>123</average>

      </category>

     </categories>

     <totalGoal>45446</totalGoal>

     <totalAmount>243</totalAmount>

    </categoryType>

   </categoryTypes>

   <groupId>sfsfd</groupId>

   <groupName>safd</groupName>

  </group>

 </groups>

 <thresholdBalance>2000</thresholdBalance>

 <fromDate>25-02-2020</fromDate>

 <toDate>25-02-2020</toDate>

 <goals>

  <goal>

   <id>100</id>

   <name>Kartik</name>

   <completionDate>25-02-2020</completionDate>

   <targetAmount>10000</targetAmount>

   <targetAmountCurrency></targetAmountCurrency>

   <saveAmount>2000</saveAmount>

   <saveAmountCurrency>123</saveAmountCurrency>

   <remainingAmount>8000</remainingAmount>

   <remainingAmountCurrency>123</remainingAmountCurrency>

   <nextContributionDate>25-02-2016</nextContributionDate>

   <status>inprogress</status>

   <timeLeft>25</timeLeft>

   <targetDate>25-02-2015</targetDate>

   <projectedSavedAmount>2000</projectedSavedAmount>

   <percentage>20</percentage>

  </goal>

 </goals>

</Data>

 

 

convert xml to String
convert xml to String



 

Post a Comment

0 Comments