Display xml file in Pane

I have a properties file from which i retreive values and display in JEditorPane.

htmlPage = new JEditorPane("text/html",
                                       "<html><body> " + message +
                                       "</body></html>");

Now instead of properties file i want to use a xml file(which uses a xsl file). How do i mention it here. If i do something like

htmlPage = new JEditorPane("text/html",
                                       " test.xml");

it displays "text.xml" in the editor and not its contents.

LVL 8
thomas908Asked:
Who is Participating?
 
girionisCommented:
Try this:

StreamResult result = new StreamResult(new StringWriter());

Instead of:

Result result = new StreamResult(new StringWriter());
0
 
sudhakar_koundinyaCommented:
Syntax is JEditorPane(String type, String text)

You can't load the file directly like that
0
 
girionisCommented:
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
sudhakar_koundinyaCommented:
        StringBuffer sb=new StringBuffer();
 try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;

        while ((str = in.readLine()) != null) {
           sb.append(str);
        }
        in.close();
    } catch (IOException e) {
    }

htmlPage = new JEditorPane("text/html",
                                       sb.toString());
0
 
sudhakar_koundinyaCommented:
   StringBuffer sb = new StringBuffer();
    try {
      BufferedReader in = new BufferedReader(new FileReader("properties.xml"));
      String str;

      while ( (str = in.readLine()) != null) {
        sb.append(str);
      }
      in.close();
    }
    catch (IOException e) {
    }

    htmlPage = new JEditorPane("text/html",
                               sb.toString());
0
 
sudhakar_koundinyaCommented:
0
 
thomas908Author Commented:
thanks for replying.
Doesn't work. I displays a blank EditorPane. If i give absolute path then it dispalys part of xml document (but not the contents using xsl as i want)
0
 
girionisCommented:
Have you tried my example (the link I posted)?
0
 
thomas908Author Commented:
>>Have you tried my example (the link I posted)?

 Can't make it work
0
 
thomas908Author Commented:
Sorry, Can't make out what's "documentBuilder" mentioned in the code
0
 
thomas908Author Commented:
Would it be feasible is i convert xml to html and then display it in JEditorPane
0
 
girionisCommented:
DocumentBuilder is a class that deals with XML. You can't just put the whole file into a pane, as it is. You will need to read it into memory first (that's what DocumentBuilder is doing) and then append it. I think the links I posted has documentation.

> Would it be feasible is i convert xml to html and then display it in JEditorPane

Yes you could that to: http://javaalmanac.com/egs/javax.xml.transform/BasicXsl.html but you will still need to parse the XML file.
0
 
thomas908Author Commented:
>>DocumentBuilder is a class that deals with XML

Sorry, coudn't get how they are using it

 // Parse the xml file
   inputDoc=documentBuilder.parse(xmlFile);

Thought probably documentBuilder was a DocumentBuilder object but its constructor is protected, so can't make an object. Can't extend it as I am already extending JFrame.

0
 
girionisCommented:
You getan instance of DocumentBuilder through a DocumentBuilderFactory: http://javaalmanac.com/egs/javax.xml.parsers/BasicDom.html
0
 
thomas908Author Commented:
Thanks for the quick response.
0
 
thomas908Author Commented:
Tried everything.Still getting the same blank window
here's my code

private static void showWindow(String windowPath) {
        /**Bundle to read the panel specific file*/
        ResourceBundle resource;
        try {
            JFrame f = new JFrame();
            f.setLocation( -1000, -1000);
            safetyWindow = new SafetyWindow();
            resource = ResourceBundle.getBundle(SystemConstants.PATH +
                                                windowPath, Language.getLocale());

            /* Title of the warning window */
            String title = resource.getString("title");

            /* Message to be displayed inside the warning window */
//            String message = resource.getString("body");

            safetyWindow.setTitle(title);
            htmlPage = new JEditorPane("text/html");
            File xmlFile = new File("cell.xml");

            htmlPage.setText("");


            // Convert the xml document to string for display
            try {
                 DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
                 Document inputDoc = documentBuilder.newDocumentBuilder().parse(xmlFile);
                 htmlPage.setText(documentToString(inputDoc));
            }
            catch (TransformerException e){
                 e.printStackTrace();
               }


            htmlPage.setEditable(false);
            //safetyWindow.setModal(true);
            JScrollPane scrollPane = new JScrollPane(htmlPage);
            safetyWindow.getContentPane().add(scrollPane, BorderLayout.CENTER);
            //safetyWindow.add(scrollPane, BorderLayout.CENTER);

        } catch (Exception e) {
            logger.fatal("showWindow():Exception" + e);
        }

        JPanel jPanel = new JPanel();
        jPanel.setBackground(Color.lightGray);
        okBtn = new JButton(Language.getMessage("ok"));
        jPanel.add(okBtn);
        okBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                safetyWindow.setVisible(false);
                safetyWindow.dispose();

            }
        });
        safetyWindow.getContentPane().add(jPanel, BorderLayout.SOUTH);
        //safetyWindow.add(jPanel, BorderLayout.SOUTH);

        Dimension screenSize = safetyWindow.getToolkit().getScreenSize();
        int width = screenSize.width * 8 / 20;
        int height = screenSize.height * 8 / 20;
        safetyWindow.setBounds(width / 8, height / 8, width, height);
        safetyWindow.setVisible(true);
        safetyWindow.toFront();

    }



    private static String documentToString(org.w3c.dom.Document doc) throws TransformerException {

        // Create dom source for the document
        DOMSource domSource=new DOMSource(doc);

        // Create a string writer
        StringWriter stringWriter=new StringWriter();

        // Create the result stream for the transform
        StreamResult result = new StreamResult(stringWriter);

        // Create a Transformer to serialize the document
        TransformerFactory tFactory =TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty("indent","yes");

        // Transform the document to the result stream
        transformer.transform(domSource, result);
        return stringWriter.toString();
    }

0
 
thomas908Author Commented:
Thanks for the help.
Sorry missed it.

There was an Exception. corrected it and it now displays the xml doc in the window. Still not using the xsl to display the required result.
0
 
thomas908Author Commented:
This is what i see in teh window. But i want it to use the xsl to display it correctly

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="cell.xsl"?>

<doc>
     <title>warning</title>
     <body>
       <val>1</val>
     </body>
     <body>
       <val> 2</val>
    </body>
    </doc>
0
 
girionisCommented:
0
 
thomas908Author Commented:
Is this to be used in combination with the above code?
0
 
girionisCommented:
Not necessarily, you do not have to use the DocumentBuilder to parse the XML file again.
0
 
thomas908Author Commented:
Would it be something similar to this

    private static void showWindow(String windowPath) {
        /**Bundle to read the panel specific file*/
        ResourceBundle resource;
        try {
            JFrame f = new JFrame();
            f.setLocation( -1000, -1000);
            safetyWindow = new SafetyWindow();
            resource = ResourceBundle.getBundle(SystemConstants.PATH +
                                                windowPath, Language.getLocale());

            /* Title of the warning window */
            String title = resource.getString("title");

            /* Message to be displayed inside the warning window */
//            String message = resource.getString("body");

            safetyWindow.setTitle(title);
            htmlPage = new JEditorPane();
            File xmlFile = new File("cell.xml");

//            htmlPage.setText("");

            // Parse the xml file


            // Convert the xml document to string for display
             Document inputDoc;
            try {
                 DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
                 inputDoc = documentBuilder.newDocumentBuilder().parse(xmlFile);
                 htmlPage.setText(documentToString(inputDoc));
            }
            catch (TransformerException e){
                 e.printStackTrace();
               }


            htmlPage.setEditable(false);
            /****************/
              TransformerFactory factory = TransformerFactory.newInstance();

               // Use the factory to create a template containing the xsl file
               Templates template = factory.newTemplates(new StreamSource(
                   new FileInputStream("cell.xsl")));

               // Use the template to create a transformer
               Transformer xformer = template.newTransformer();

               // Prepare the input and output files
               Source source = new StreamSource(new FileInputStream("cell.xml"));


               // Apply the xsl file to the source file and write the result to the output file
               xformer.transform(source,);


            /********************/

            //safetyWindow.setModal(true);
            JScrollPane scrollPane = new JScrollPane(htmlPage);
            safetyWindow.getContentPane().add(scrollPane, BorderLayout.CENTER);
            //safetyWindow.add(scrollPane, BorderLayout.CENTER);

        } catch (Exception e) {
            logger.fatal("showWindow():Exception" + e);
        }

        JPanel jPanel = new JPanel();
        jPanel.setBackground(Color.lightGray);
        okBtn = new JButton(Language.getMessage("ok"));
        jPanel.add(okBtn);
        okBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                safetyWindow.setVisible(false);
                safetyWindow.dispose();

            }
        });
        safetyWindow.getContentPane().add(jPanel, BorderLayout.SOUTH);
        //safetyWindow.add(jPanel, BorderLayout.SOUTH);

        Dimension screenSize = safetyWindow.getToolkit().getScreenSize();
        int width = screenSize.width * 8 / 20;
        int height = screenSize.height * 8 / 20;
        safetyWindow.setBounds(width / 8, height / 8, width, height);
        safetyWindow.setVisible(true);
        safetyWindow.toFront();

    }

0
 
thomas908Author Commented:
How do i set the text with output generated from using hte xsl file.
Something like

  xformer.transform(source,htmlPage.setText(documentToString(inputDoc)));

is not possible.
0
 
girionisCommented:
You need a Result type of object. Try the following and tell me if ti helps:

Result result = new StreamResult(new StringWriter());
xformer.transform(source, result));
StringWriter writer = result.getWriter();
htmlPage.setText(writer.getBuffe().toString());
0
 
girionisCommented:
The getBuffe() should be getBuffer()
0
 
thomas908Author Commented:
StringWriter writer = result.getWriter();


Error #: 300 : method getWriter() not found in interface javax.xml.transform.Result at line 130, column 43
0
 
thomas908Author Commented:
Thanks
That is close.
It displays the html doc like

<html>
<body>
<h2>warning123</h2>
<table border="1">
<tr>
<td>C1</td>
</tr>
<tr>
<td>C2</td>
</tr>
</table>
</body>
</html>

I just need it to display the result to the user. Like what this table will look in a browser.
0
 
girionisCommented:
Can you set the content to text/html?
0
 
girionisCommented:
htmlPage.setContentType("text/html");
0
 
thomas908Author Commented:
Thank you so much girionis.
It was so nice of you to spend so much time and effort to solve my problem.
Thanks a lot
0
 
girionisCommented:
Thank you for accepting, glad I was of help :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.