Extracting attribute values from XML elements
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 Main {
public static void main(String[] argv) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
SaxHandler handler = new SaxHandler();
parser.parse("sample.xml", handler);
}
}
class SaxHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName, Attributes attrs)
throws SAXException {
if (qName.equals("order")) {
String date = attrs.getValue("date");
String number = attrs.getValue("number");
System.out.println("Order #" + number + " date is '" + date + "'");
}
}
}
Related examples in the same category