• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

parsing xml (SAX) problem

Hi,
I'm trying to get value type of Employee but it seem like the startElement([..]) is not read ("aaaa" is not printed).

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();

              sp.parse("http://www.totheriver.com/learn/xml/code/employees.xml", this);

----------------------
public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        //reset
            System.out.println("aaaaa");

       if(qName.equalsIgnoreCase("Employee")) {
   
           String s = attributes.getValue("type").toString();
            System.out.println(attributes.getValue("type"));

        }
    }

Open in new window


0
static86
Asked:
static86
1 Solution
 
for_yanCommented:

This code works for me
(it may be a bit different than yours):

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.net.URI;
import java.net.URL;
import java.util.Calendar;

public class ParseWithSax extends DefaultHandler {

    public static void main(String [] args){
        Calendar.getInstance().setTimeInMillis(100L);

           Calendar.getInstance().setTimeInMillis(-100L);

        new ParseWithSax().parseDocument();
    }
    	private void parseDocument() {

		//get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {

			//get a new instance of parser
			SAXParser sp = spf.newSAXParser();
  
            sp.parse("http://www.totheriver.com/learn/xml/code/employees.xml", this);

		}catch(SAXException se) {
			se.printStackTrace();
		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}  catch(Exception exx){
            exx.printStackTrace();
        }
	}

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        //reset
            System.out.println("aaaaa");

       if(qName.equalsIgnoreCase("Employee")) {

           String s = attributes.getValue("type").toString();
            System.out.println(attributes.getValue("type"));

        }
    }


}

Open in new window




aaaaa
aaaaa
permanent
aaaaa
aaaaa
aaaaa
aaaaa
contract
aaaaa
aaaaa
aaaaa
aaaaa
permanent
aaaaa
aaaaa
aaaaa

Open in new window

0
 
static86Author Commented:
Thanks, it worked! I it was, probably the matter of imports.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now