Solved

SAX, DOM or Xpath

Posted on 2007-03-29
9
259 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 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

738 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