XML parsen
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; 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 XMLDemo { ArrayList<Address> addresses = new ArrayList<>(); public XMLDemo() { String xml = "<addresses>" + "<address>" + "<name>Hugo</name>" + "<age>42</age>" + "</address>" + "<address>" + "<name>Trude</name>" + "<age>38</age>" + "</address>" + "</addresses>"; InputStream is = new ByteArrayInputStream(xml.getBytes()); try { MyXMLParser parser = new MyXMLParser(is, addresses); parser.parse(); for (Address address : addresses) { System.out.println(address); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new XMLDemo(); } } class MyXMLHandler extends DefaultHandler { StringBuffer sb = new StringBuffer(); Address address; ArrayList<Address> addresses; public MyXMLHandler(ArrayList<Address> addresses){ this.addresses = addresses; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); sb = new StringBuffer(); if (qName.equalsIgnoreCase("address")) address = new Address(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); sb.append(ch, start, length); } @Override public void endElement(String uri, String localName, String name) throws SAXException { super.endElement(uri, localName, name); if (name.equalsIgnoreCase("name")) address.setName(sb.toString()); else if (name.equalsIgnoreCase("age")) address.setAge(Integer.parseInt(sb.toString())); else if (name.equalsIgnoreCase("address")){ addresses.add(address); } } } class MyXMLParser { InputStream is; SAXParser saxParser; ArrayList<Address> addresses; public MyXMLParser(InputStream is, ArrayList<Address> addresses) throws ParserConfigurationException, SAXException { this.is = is; this.addresses = addresses; SAXParserFactory factory = SAXParserFactory.newInstance(); saxParser = factory.newSAXParser(); } public void parse() throws SAXException, IOException { MyXMLHandler handler = new MyXMLHandler(addresses); saxParser.parse(is, handler); } } class Address { private String name; private int age; public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } @Override public String toString() { return name + ", " + age; } }
Stichworte:
XML parsen lesen