Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I can use java and sax I am trying to parse the file below. I want to print the

ID: 3537849 • Letter: I

Question

I can use java and sax



I am trying to parse the file below. I want to print the id and name of each passenger. Can some one give me code to parse it ?

<?xml version="1.0" encoding="utf-8"?>
<root xmlns:android="www.google.com">

<passenger id = "001">
<name>Tom Cruise</name>
</passenger>

<passenger id = "002">
<name>Tom Hanks</name>
</passenger>

</root>


The problem is - In the output, I see the word passenger instead of the value of passenger id. How do i fix that ?



Java Code

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFileSAX{

public static void main(String argv[]) {

try {

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {

boolean bfname = false;
boolean blname = false;

public void startElement(String uri, String localName,String qName,
            Attributes attributes) throws SAXException {

    System.out.println("Start Element :" + qName);

    if (qName.equalsIgnoreCase("passenger id")) {
        bfname = true;
    }

    if (qName.equalsIgnoreCase("name")) {
        blname = true;
    }




}

public void endElement(String uri, String localName,
    String qName) throws SAXException {

    System.out.println("End Element :" + qName);

}

public void characters(char ch[], int start, int length) throws SAXException {

    if (bfname) {
        System.out.println("passenger id : " + new String(ch, start,   length));
        bfname = false;
    }

    if (blname) {
        System.out.println("name : " + new String(ch, start, length));
        blname = false;
    }

}

};

   saxParser.parse("c:\flight.xml", handler);

} catch (Exception e) {
   e.printStackTrace();
   }

   }

}


Explanation / Answer

In the startElement, when it's for "passenger", Attributes argument you get will have that value. public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("passenger") && attributes != null){ System.out.println(attributes.getValue("id")); } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote