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

SAX, DOM or Xpath

Posted on 2007-03-29
9
257 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:Mayank S
ID: 18820035
So what has to do with: >> SAX, DOM or Xpath
0
 

Author Comment

by:badour_ma
ID: 18820057
thanks alot ADSLMark
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

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
 

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:Mayank S
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

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
by zero exception 10 52
XML SQL 8 27
Is there a simpler dropbox system? 10 34
java imports not found 4 27
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 …
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
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…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

837 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