I am new with this, so why is that when I want to print the value for the NAME element in StartElement(), for all 3 elements it prints null ?
class Test {
public static void main(String args[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equals("NAME")) {
String str = attributes.getValue("NAME");
System.out.println(str);
}
}
};
saxParser.parse(new InputSource(new StringReader(xmlString)), handler);
} catch (Exception e) {
e.printStackTrace();
}
}
static String xmlString = "<PHONEBOOK>" +
" <PERSON>" +
" <NAME>Joe Wang</NAME>" +
" <EMAIL>joe@yourserver.com</EMAIL>" +
" <TELEPHONE>202-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON> " +
"<NAME>Karol</NAME>" +
" <EMAIL>karol@yourserver.com</EMAIL>" +
" <TELEPHONE>306-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON>" +
" <NAME>Green</NAME>" +
" <EMAIL>green@yourserver.com</EMAIL>" +
" <TELEPHONE>202-414-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" </PHONEBOOK>";
}
Your XML doesn’t have any attributes. So this:
… is never going to print anything out.
You want to print out the content of the NAME element, by the looks of it. So you’d want to handle the
charactersevent when you’re in the NAME element.Do you have to use SAX, by the way? In my experience it’s a pain in the neck compared with using a DOM-like model (e.g. using JDOM or another API – the built-in one is somewhat painful).
An alternative approach if you’re in control of the XML is to start using attributes:
Then you can use
attributes.getValue("NAME")when you get aPERSONelement.