Solved

Display xml file in Pane

Posted on 2004-08-23
31
350 Views
Last Modified: 2010-03-31
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.

0
Comment
Question by:thomas908
  • 15
  • 12
  • 4
31 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11869194
Syntax is JEditorPane(String type, String text)

You can't load the file directly like that
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869197
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11869201
        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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11869222
   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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11869231
0
 
LVL 8

Author Comment

by:thomas908
ID: 11869285
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
 
LVL 35

Expert Comment

by:girionis
ID: 11869438
Have you tried my example (the link I posted)?
0
 
LVL 8

Author Comment

by:thomas908
ID: 11878285
>>Have you tried my example (the link I posted)?

 Can't make it work
0
 
LVL 8

Author Comment

by:thomas908
ID: 11878379
Sorry, Can't make out what's "documentBuilder" mentioned in the code
0
 
LVL 8

Author Comment

by:thomas908
ID: 11878420
Would it be feasible is i convert xml to html and then display it in JEditorPane
0
 
LVL 35

Expert Comment

by:girionis
ID: 11878494
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
 
LVL 8

Author Comment

by:thomas908
ID: 11879412
>>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
 
LVL 35

Expert Comment

by:girionis
ID: 11879444
You getan instance of DocumentBuilder through a DocumentBuilderFactory: http://javaalmanac.com/egs/javax.xml.parsers/BasicDom.html
0
 
LVL 8

Author Comment

by:thomas908
ID: 11879449
Thanks for the quick response.
0
 
LVL 8

Author Comment

by:thomas908
ID: 11879491
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 8

Author Comment

by:thomas908
ID: 11879504
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
 
LVL 8

Author Comment

by:thomas908
ID: 11879512
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
 
LVL 35

Expert Comment

by:girionis
ID: 11879629
0
 
LVL 8

Author Comment

by:thomas908
ID: 11879661
Is this to be used in combination with the above code?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11879694
Not necessarily, you do not have to use the DocumentBuilder to parse the XML file again.
0
 
LVL 8

Author Comment

by:thomas908
ID: 11879728
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
 
LVL 8

Author Comment

by:thomas908
ID: 11879906
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
 
LVL 35

Expert Comment

by:girionis
ID: 11880093
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
 
LVL 35

Expert Comment

by:girionis
ID: 11880096
The getBuffe() should be getBuffer()
0
 
LVL 8

Author Comment

by:thomas908
ID: 11880232
StringWriter writer = result.getWriter();


Error #: 300 : method getWriter() not found in interface javax.xml.transform.Result at line 130, column 43
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
ID: 11880299
Try this:

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

Instead of:

Result result = new StreamResult(new StringWriter());
0
 
LVL 8

Author Comment

by:thomas908
ID: 11880340
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
 
LVL 35

Expert Comment

by:girionis
ID: 11880395
Can you set the content to text/html?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11880402
htmlPage.setContentType("text/html");
0
 
LVL 8

Author Comment

by:thomas908
ID: 11880489
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
 
LVL 35

Expert Comment

by:girionis
ID: 11880493
Thank you for accepting, glad I was of help :)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

760 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

18 Experts available now in Live!

Get 1:1 Help Now