import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class DomParserExample { public static void main(String[] args) { try { DOMParser parser = new DOMParser(); System.out.println("Root element: " + rootElement.getNodeName()); System.out.println("Number of books: " + nodeList.getLength()); for (int i = 0; i < nodeList.getLength(); i++) { Element bookElement = (Element) nodeList.item(i); String title = bookElement.getElementsByTagName("title").item(0).getTextContent(); String author = bookElement.getElementsByTagName("author").item(0).getTextContent(); String year = bookElement.getElementsByTagName("year").item(0).getTextContent(); System.out.println("Book " + (i + 1) + ": " + title + " by " + author + ", published in " + year); } } catch (Exception e) { e.printStackTrace(); } } } import org.apache.xerces.parsers.SAXParser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SaxParserExample { public static void main(String[] args) { try { SAXParser parser = new SAXParser(); } catch (Exception e) { e.printStackTrace(); } } } class CustomHandler extends DefaultHandler { boolean inTitle = false; boolean inAuthor = false; boolean inYear = false; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("title")) { inTitle = true; } else if (qName.equalsIgnoreCase("author")) { inAuthor = true; } else if (qName.equalsIgnoreCase("year")) { inYear = true; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (inTitle) { System.out.println("Title: " + new String(ch, start, length)); inTitle = false; } else if (inAuthor) { System.out.println("Author: " + new String(ch, start, length)); inAuthor = false; } else if (inYear) { System.out.println("Year: " + new String(ch, start, length)); inYear = false; } } }


上一篇:
下一篇:
切换中文