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

help me in my java code

Posted on 2007-03-28
15
216 Views
Last Modified: 2010-03-31
Hi,
I wrote a java file that parse the XML document using SAX parser. But I want to print the edition date if the publisher is “Oracle Publishing”
So how can I do that in my public void characters (char ch[], int start, int length)??

<?xml version = '1.0' encoding = 'UTF-8'?>
   <catalog>
     <journal>
       <journal_title>Dell</journal_title>
       <publisher>Oracle Publishing</publisher>
       <edition>Sept-Oct 2003</edition>
       <article_section>XML</article_section>
       <title>Parsing XML Efficiently</title>
       <author>Julie Basu</author>
    </journal>
    <journal>
      <journal_title>Oracle Magazine</journal_title>
      <publisher>Oracle Publishing</publisher>
      <edition>Nov-Dec 2003</edition>
      <article_section>SQL</article_section>
      <title>The Active Database</title>
      <author> Cameron ORourke </author>
    </journal>
   </catalog>

package com.psol.xbe2;
import java.io.FileReader;
import java.lang.String;

import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.helpers.DefaultHandler;


public class MySAXApp1 extends DefaultHandler
{

    public static void main (String args[])
      throws Exception
    {
      XMLReader xr = XMLReaderFactory.createXMLReader();
      MySAXApp1 handler = new MySAXApp1();
      xr.setContentHandler(handler);
      xr.setErrorHandler(handler);

                        // Parse each file provided on the
                        // command line.
      for (int i = 0; i < args.length; i++) {
          FileReader r = new FileReader(args[i]);
          xr.parse(new InputSource(r));
      }
    }


    public MySAXApp1 ()
    {
      super();
    }


    ////////////////////////////////////////////////////////////////////
    // Event handlers.
    ////////////////////////////////////////////////////////////////////


    public void startDocument ()
    {
      System.out.println("Start document");
    }


    public void endDocument ()
    {
      System.out.println("End document");
    }


    public void startElement (String uri, String name,
                        String qName, Attributes atts)
    {
      //if ("".equals (uri))
      //    System.out.println("Start element: " + qName);
      //else
         // System.out.println("Start element: {" + uri + "}" + name);
    }


    public void endElement (String uri, String name, String qName)
    {
      // if ("".equals (uri))
        //  System.out.println("End element: " + qName);
      //else
        //  System.out.println("End element:   {" + uri + "}" + name);
    }


    public void characters (char ch[], int start, int length)
    {
    String a;
   
   
      //System.out.print("Characters:    \"");
            a= String.valueOf (ch, start,length);
             if (a.equals("Oracle Publishing "))
System.out.print("XXXX"+ a+ "XXXX");
// here I want to print the edtion date- how can I call the element that follow

      //System.out.print("\"\n");
          }
    }

0
Comment
Question by:badour_ma
  • 7
  • 4
  • 3
  • +1
15 Comments
 
LVL 14

Expert Comment

by:boonleng
ID: 18808439
The method characters(...) is reading the value character by character, so you need to store all the characters to CharArrayWriter variable and print it out at endElement(...).

Example:

public class MySAXApp1 extends DefaultHandler {

    private CharArrayWriter contents;

    public void startDocument ()
    {
        contents = new CharArrayWriter();
    }

    public void startElement (String uri, String name, String qName, Attributes atts)
    {
        contents.reset();
    }

    public void endElement (String uri, String name, String qName)
    {
        String s = contents.toString();
        if ("publisher".equals (qName) && "Oracle Publishing".equals(s)) {
            // here I want to print the edtion date
        }
    }

    public void characters (char ch[], int start, int length)
    {
        contents.write(ch, start, length);
    }
}
0
 

Author Comment

by:badour_ma
ID: 18808517
hi boonleng,
thanks alot but I alrady use ValueOf() to get the string and its works
I am asking how to print the edition data when i find the  Oracle Publishing??
0
 
LVL 14

Expert Comment

by:boonleng
ID: 18808737
Sorry, didn't see that you are using ValueOf().

Coz Sax Parser is reading from top to bottom, so you need to put an indicator/flag to tell next element to print the edition date.
Example:

public class MySAXApp1 extends DefaultHandler {

    private boolean isOracle = false;

    public void endElement (String uri, String name, String qName)
    {
        if ("edition".equals (qName)) {
            isOracle = false;
        }
    }

    public void characters (char ch[], int start, int length)
    {
        String a;
        //System.out.print("Characters:    \"");
        a= String.valueOf (ch, start,length);
       
        if (isOracle) {
        // here I want to print the edtion date
        }
        else if (a.equals("Oracle Publishing ")) {
             isOracle = true;
        }
    }
}

Hope this help.
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.

 
LVL 14

Expert Comment

by:boonleng
ID: 18808832
This is just a temporary solution, not a very good way of doing it.
If the position of the "edition" element changed, then you will encounter problem.

I would suggest that read the entire XML and store everything into beans/maps, and later loop the list of beans to print the data out.
Another way is to use XPath to read the data, this way you can navigate the XML wherever you want.
0
 

Author Comment

by:badour_ma
ID: 18809146
Hi again boonleng,
thanks for helping me.
who about if I want to print the data of second element after "Oracle Publishing" what ever the element is. so the most important is the position of the element not the element it self.
So how can I print the data of the element fount after Oracle Publishing???
0
 
LVL 13

Expert Comment

by:kawas
ID: 18810932
keep a flag and when you encounter the starting element publisher set the flag to true. do that in startElement (). every time startElement is called, check if the flag is true, if so, you have the next element. do what ever with it and then set the flag back to false.
0
 

Author Comment

by:badour_ma
ID: 18814525
hi Kawas
can u please show me how to do that by code?
0
 

Author Comment

by:badour_ma
ID: 18814969
hi I wrote this code to set a flage if the elment data is "XML" and to print the data of the second elemnt but I had the following error:
MySAXApp1.java:84: variable x might not have been initialized
                if (x==1)
                    ^
but I can not intilize x coz if I do that I will lose the flage value!!!!
 public void characters (char ch[], int start, int length)
    {
    String a;
    int x;
   
      //System.out.print("Characters:    \"");

            a= String.valueOf (ch, start,length);
            
            if (x==1)
            {
            System.out.print("yyy"+ a+ "yyy");
            x=0;
            }
            
             if (a.equals("XML"))
             {
System.out.print("XXXX"+ a+ "XXXX");
x=1;}

      //System.out.print("\"\n");
          }
   

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18815368
SAX is not appropriate for this - you need DOM. Use XPath
0
 

Author Comment

by:badour_ma
ID: 18816561
hi CEHJ
can u please help me to write the code in DOM. How can I change it??
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
ID: 18816766
See http://www.experts-exchange.com/Programming/Languages/Java/Q_22476035.html#a18803525

Your XPath would be

"//journal[publisher='Oracle Publishing']/edition/text()"

which i've just tested successfully
0
 

Author Comment

by:badour_ma
ID: 18816920
but CEHJ I do not know waht is the elements name I only know that if I find 'Oracle Publishing' as data in one of the elemnts then I have to print the data in the next element???
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18817413
>>but CEHJ I do not know waht is the elements name

I thought you said it was 'edition'?
0
 

Author Comment

by:badour_ma
ID: 18819323
hi CEHJ
I said edtion for example but as I said befor I am looking for certin data 'Oracle Publishing' and when I find it I have to print the next data in the next element. So both I do not know what is the elemnt name??!!
So do I still have to use Xpath??
0
 
LVL 14

Accepted Solution

by:
boonleng earned 450 total points
ID: 18821624
You still can use XPath to find the value.
Example:

            List list = source.selectNodes("//*[. = 'Oracle Publishing']");
            for (Iterator iter = list.iterator(); iter.hasNext();) {
                Node node = (Node) iter.next();
                System.out.println(node.getText());
                System.out.println(node.valueOf("following-sibling::*[1]/text()"));
               
            }

but is best that you can have the element name, so that you wont get the wrong data (e.g the title or author or...etc elements might be having the same value of 'Oracle Publishing').
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
V.simple question about Android packages and libraries 1 29
Adding multiple JVM environments to RedHat 6 7 47
CSV file parsing thru Java 13 34
Java: anonymous class 4 29
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
The viewer will learn how to implement Singleton Design Pattern in Java.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

840 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