Solved

How to convert XML file into String?

Posted on 2014-02-13
6
580 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

911 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now