help me in my java code

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");
          }
    }

badour_maAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

boonlengCommented:
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
badour_maAuthor Commented:
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
boonlengCommented:
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
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

boonlengCommented:
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
badour_maAuthor Commented:
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
kawasCommented:
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
badour_maAuthor Commented:
hi Kawas
can u please show me how to do that by code?
0
badour_maAuthor Commented:
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
CEHJCommented:
SAX is not appropriate for this - you need DOM. Use XPath
0
badour_maAuthor Commented:
hi CEHJ
can u please help me to write the code in DOM. How can I change it??
0
CEHJCommented:
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
badour_maAuthor Commented:
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
CEHJCommented:
>>but CEHJ I do not know waht is the elements name

I thought you said it was 'edition'?
0
badour_maAuthor Commented:
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
boonlengCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

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.