Solved

help me in my java code

Posted on 2007-03-28
15
212 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 14

Expert Comment

by:boonleng
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
hi Kawas
can u please show me how to do that by code?
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:badour_ma
Comment Utility
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
Comment Utility
SAX is not appropriate for this - you need DOM. Use XPath
0
 

Author Comment

by:badour_ma
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
>>but CEHJ I do not know waht is the elements name

I thought you said it was 'edition'?
0
 

Author Comment

by:badour_ma
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

771 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

10 Experts available now in Live!

Get 1:1 Help Now