?
Solved

SAX, DOM or Xpath

Posted on 2007-03-29
9
Medium Priority
?
261 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
[X]
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
  • 4
  • 3
  • 2
9 Comments
 
LVL 10

Accepted Solution

by:
ADSLMark earned 2000 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
Interactive Way of Training for the AWS CSA Exam

An interactive way of learning that will help you visualize core concepts so that you can be more effective when taking your AWS certification exam.  Built for students by a student to help them understand the concepts that they are being taught.

 

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month11 days, 23 hours left to enroll

752 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