Java by API/javax.xml.parsers/SAXParser — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 14:22, 31 мая 2010
SAXParser: parse(InputSource is, DefaultHandler dh)
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MainClass {
public static void main(String args[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (name) {
System.out.println("Name: " + new String(ch, start, length));
name = false;
}
}
};
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.ru</EMAIL>" +
" <TELEPHONE>202-999-9999</TELEPHONE>" +
" <WEB>www.jexp.ru</WEB>" +
" </PERSON>" +
" <PERSON> " +
"<NAME>Karol</NAME>" +
" <EMAIL>karol@yourserver.ru</EMAIL>" +
" <TELEPHONE>306-999-9999</TELEPHONE>" +
" <WEB>www.jexp.ru</WEB>" +
" </PERSON>" +
" <PERSON>" +
" <NAME>Green</NAME>" +
" <EMAIL>green@yourserver.ru</EMAIL>" +
" <TELEPHONE>202-414-9999</TELEPHONE>" +
" <WEB>www.jexp.ru</WEB>" +
" </PERSON>" +
" </PHONEBOOK>";
}