Solved

How to convert XML file into String?

Posted on 2014-02-13
6
597 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
[X]
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
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
junit example issue 2 26
Problems moving Excel files from local drive to server 4 33
CSV file copy field 1 to field 2 2 42
Java Inheritance super keyword use 8 37
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.
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…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

733 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