Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

How to convert XML file into String?

Posted on 2014-02-13
6
595 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

790 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