Solved

How to convert XML file into String?

Posted on 2014-02-13
6
586 Views
Last Modified: 2014-02-14
Hi,

When I run below code it is not reading file, the document object is null. What I want to do is to read a file and then convert it into sgtring.

File file = new File("C:\\Product\\abcd.xml");
       
        if (file.exists()) {
              
              System.out.println("File Exits   " + file.getAbsolutePath());
        }
       
    String content = "";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
       // Document document = builder.parse(new FileInputStream(file));
        Document document = builder.parse(new FileInputStream(file));


        TransformerFactory tranFactory = TransformerFactory.newInstance();
        Transformer aTransformer = tranFactory.newTransformer();
        aTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                "yes");
        aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        Source src = new DOMSource(document);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Result dest = new StreamResult(stream);
        aTransformer.transform(src, dest);
        content = stream.toString();
       
        System.out.println("String is ....");
       
    } catch (ParserConfigurationException e) {
        //logger.error(e.getMessage(), e);
    } catch (SAXException e) {
        //logger.error(e.getMessage(), e);
    } catch (IOException e) {
       // logger.error(e.getMessage(), e);
    } catch (TransformerConfigurationException e) {
        //logger.error(e.getMessage(), e);
    } catch (TransformerException e) {
       // logger.error(e.getMessage(), e);
    }
    return content;
   }
0
Comment
Question by:AliAjoo
6 Comments
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 107 total points
ID: 39858192
There doesn't appear to be any issues with the code, other than the poor error handling.
When I run below code it is not reading file, the document object is null
How do you know that "document" is null? Are you running this in a debugger?


Ahh, or by the above do you actually mean that the return value of this method (ie. the "content" variable in the above code) is null? That is more likely the case, but for us (or even you) to figure it out, you will have to STOP ignoring any exceptions that might be thrown, as you are currently doing, and at the very least print the stack traces so that you can see what is going on.

Add the following line inside ALL the "catch" blocks in the above code, and run it again...
e.printStackTrace();

Open in new window

0
 

Author Comment

by:AliAjoo
ID: 39859327
thnaks for your resposne.

I am attaching a sample XML file. It is stored under C:\\Product\\student.xml. When I run the above program it shoud print xml contents?

Ali
student.xml
0
 
LVL 32

Expert Comment

by:awking00
ID: 39859370
Are you using Eclipse? Do you have it?
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:AliAjoo
ID: 39860215
Yes, I am using eclipse and also the file is present in the directory
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 108 total points
ID: 39860234
http://technojeeves.com/joomla/index.php/free/137-serialize-xml-to-file-in-java

With variant

public static String saveToString(Document doc) {
        StringWriter out = null;

        try {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            lsSerializer.getDomConfig()
                        .setParameter("format-pretty-print", Boolean.TRUE);

            LSOutput output = domImplementation.createLSOutput();
            output.setEncoding(System.getProperty("file.encoding"));
            out = new StringWriter();
            output.setCharacterStream(out);
            lsSerializer.write(doc, output);

            return out.toString();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) { /* ignore */
                }
            }
        }
    }

Open in new window

0
 

Author Closing Comment

by:AliAjoo
ID: 39860908
It was really helpful
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
print map entry 34 67
use lov values 2 49
hibernate example issues from command prompt 10 41
jsp login check 12 30
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question