Reputation: 20078
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>[email protected]</EMAIL>" +
" <TELEPHONE>202-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON> " +
"<NAME>Karol</NAME>" +
" <EMAIL>[email protected]</EMAIL>" +
" <TELEPHONE>306-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON>" +
" <NAME>Green</NAME>" +
" <EMAIL>[email protected]</EMAIL>" +
" <TELEPHONE>202-414-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" </PHONEBOOK>";
}
Upvotes: 0
Views: 1128
Reputation: 89199
That's because you're trying to read the attribute from the <NAME>
element (which doesn't have any attribute).
String str = attributes.getValue("NAME");
To read the content of the <NAME>
element, you will have to override the characters (char ch[], int start, int length)
method of DefaultHandler
and display all the ch[]
(character array) returned.
Upvotes: 1
Reputation: 1503090
Your XML doesn't have any attributes. So this:
String str = attributes.getValue("NAME");
System.out.println(str);
... 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 characters
event 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:
<PERSON NAME="Joe Wang"
EMAIL="[email protected]"
TELEPHONE="202-999-9999"
WEB="www.java2s.com" />
Then you can use attributes.getValue("NAME")
when you get a PERSON
element.
Upvotes: 1