java domparser



public class DOMParser {

   private static String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
              + "<catalog>"
              + "<book id=\"1\">"
              + "<author>Charles Dickens</author>"
              + "<title>Oliver Twist</title>"
              + "</book>"
              + "<book id=\"2\">"
              + "<author>Mark Twain</author>"
              + "<title>The Adventures of Tom Sawyer</title>"
              + "</book>"
              + "</catalog>";

public static void main(String[] args) throws Exception {
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
NodeList books = doc.getElementsByTagName("book");
for (int i = 0; i < books.getLength(); i++) {
Element book = (Element) books.item(i);
Node title = book.getElementsByTagName("title").item(0);
System.out.println(title.getTextContent());
}
}

你可能感兴趣的:(java domparser)