Solved

SAX, DOM or Xpath

Posted on 2007-03-29
9
252 Views
Last Modified: 2008-03-06
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 it did not work
so I do not know waht is the elements name I only know that if I find" XML"as data in one of the elemnts then I have to print the data in the next element???
 
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
{
      private boolean isOracle = false;

    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 (isOracle)
            {
            System.out.print("yyy"+ a+ "yyy");
            isOracle = false;

            }
            
             if (a.equals("XML"))
             {
System.out.print("XXXX"+ a+ "XXXX");
isOracle = true;}

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

The XML document
<?xml version = '1.0' encoding = 'UTF-8'?>
   <catalog>
     <journal>
       <journal_title>Open:</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>
0
Comment
Question by:badour_ma
  • 4
  • 3
  • 2
9 Comments
 
LVL 10

Accepted Solution

by:
ADSLMark earned 500 total points
ID: 18820012
This works:

package com.psol.xbe2;

import java.io.*;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class MySAXApp1
    extends DefaultHandler
{
    private boolean foundXML;
    private boolean insideTag;

    public MySAXApp1()
    {
        this.foundXML = false;
        this.insideTag = false;
    }

    public void startElement(String uri, String name, String qName, Attributes atts)
    {
        this.insideTag = true;
    }

    public void endElement(String uri, String name, String qName)
    {
        this.insideTag = false;
    }

    public void characters(char ch[], int start, int length)
    {
        String data = String.valueOf(ch, start, length);

        if(this.insideTag && this.foundXML)
        {
            System.out.print("Data in next tag after founding 'XML': "+data);
            this.foundXML = false;
        }

        if(data.equals("XML"))
            this.foundXML = true;
    }

    //Program entry
    public static void main (String args[])
        throws Exception
    {
        MySAXApp1 handler = new MySAXApp1();

        // Create xml reader
        XMLReader xr = XMLReaderFactory.createXMLReader();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);

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

You forgot to check whether you were inside an element yes/no. Now that i've added that boolean flag, it only reads the content when inside a tag. Previous you would be reading whitespace after the tags.

Mark
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18820035
So what has to do with: >> SAX, DOM or Xpath
0
 

Author Comment

by:badour_ma
ID: 18820057
thanks alot ADSLMark
0
 

Author Comment

by:badour_ma
ID: 18820069
hi mayankeagle:
I did my code using SAX parser, So In order to get my request to I have to change it to DOM parser or to use xpath
0
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

 

Author Comment

by:badour_ma
ID: 18820124
I am facing another problem:(
I wnat to search for 15 data in one XML doucemnt !!!
ex.
XML
Java
c
c++
...
...
so it is not logical to use 15 flag!!!
what can I do???
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18820139
If you want to remember which tag you were looking for, then you could save the tag data in a String variable and use the boolean flag to signal that the previous value was interesting (and if you want to know what, print the string variable), so please get me the next value inside the upcoming tag.
So basically you only have to alter the:

if(data.equals("XML"))
    this.foundXML = true;

into sth which searches for all the strings:

if("XML".equals(data) || "HTML".equals(data) || ...)
{
    this.foundXML = true;
    this.prevValue = data;
}

Mark
0
 

Author Comment

by:badour_ma
ID: 18820252
again thank u
u seem so smart so can you please help me coz I am facing alot of problrms??
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18820290
Heh, sure I can help, but I have to go now, so I don't have time now. Anyway, there are enough people around to answer all your questions and if not I will answer them when I come back.

Mark
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18820749
>> So In order to get my request to I have to change it to DOM parser or to use xpath

http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/dom/1_read.html
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

The Problem How to write an Xquery that works like a SQL outer join, providing placeholders for absent data on the outer side?  I give a bit more background at the end. The situation expressed as relational data Let’s work through this.  I’ve …
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

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