Solved

How to convert XML file into String?

Posted on 2014-02-13
6
569 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
Comment Utility
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
Comment Utility
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 31

Expert Comment

by:awking00
Comment Utility
Are you using Eclipse? Do you have it?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:AliAjoo
Comment Utility
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
Comment Utility
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
Comment Utility
It was really helpful
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

This is an explanation of a simple data model to help parse a JSON feed
This is about my first experience with programming Arduino.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

772 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

12 Experts available now in Live!

Get 1:1 Help Now