java domparser

来源:互联网 发布:qt tcp客户端接收数据 编辑:程序博客网 时间:2024/04/29 04:14


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());
}
}

0 0
原创粉丝点击