users.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <xml-root> 4 <conn-params> 5 <conn-url>jdbc:mysql://192.168.101.7:3306/bbs</conn-url> 6 <conn-driver>com.mysql.jdbc.Driver</conn-driver> 7 <conn-username>root</conn-username> 8 <conn-password>root</conn-password> 9 </conn-params> 10 11 <person xmlns:u="http://example.org/user"> 12 <u:user> 13 <u:username>xzc</u:username> 14 <u:password>sdf23223</u:password> 15 <u:birthday>2012-01-23</u:birthday> 16 </u:user> 17 <u:user> 18 <u:username>误闯</u:username> 19 <u:password>wuchuang3223</u:password> 20 <u:birthday>2002-01-03</u:birthday> 21 </u:user> 22 </person> 23 </xml-root>
采用DOM api 解析XML
1. User类
1 public class User { 2 3 private String username; 4 private String password; 5 private String birthday; 6 7 public String toString() { 8 return "username = " + username + ", password = " + password + ", birthday = " + birthday; 9 } //省略setter,getter 10 }
2. DomUtil解析类
1 package sax.parsing.user; 2 3 import java.io.FileInputStream; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 import javax.xml.parsers.DocumentBuilder; 8 import javax.xml.parsers.DocumentBuilderFactory; 9 import javax.xml.parsers.ParserConfigurationException; 10 11 import org.w3c.dom.Document; 12 import org.w3c.dom.Element; 13 import org.w3c.dom.Node; 14 import org.w3c.dom.NodeList; 15 import org.xml.sax.InputSource; 16 17 public class DomUtil { 18 19 20 private DocumentBuilderFactory builderFactory; 21 private DocumentBuilder builder; 22 private Document document; 23 24 public DomUtil() throws ParserConfigurationException { 25 builderFactory = DocumentBuilderFactory.newInstance(); 26 builder = builderFactory.newDocumentBuilder(); 27 } 28 29 public DocumentBuilderFactory getBuilderFactory() { 30 return builderFactory; 31 } 32 public DocumentBuilder getBuilder() { 33 return builder; 34 } 35 36 public List<User> parseXml(String filepath) throws Exception { 37 38 document = builder.parse(new InputSource(new FileInputStream(filepath))); 39 40 41 List<User> list = new ArrayList<User>(); 42 43 Element root = document.getDocumentElement(); //从文档根节点获取文档根元素节点root => xml 44 NodeList childNodes = root.getChildNodes(); 45 46 for (int i=0; i<childNodes.getLength(); i++) { 47 Node node = childNodes.item(i); 48 49 /* 50 * <person> 51 <user> 52 <username>xzc</username> 53 <password>sdf23223</password> 54 <birthday>2012-01-23</birthday> 55 </user> 56 <user> 57 <username>误闯</username> 58 <password>wuchuang3223</password> 59 <birthday>2002-01-03</birthday> 60 </user> 61 </person> 62 */ 63 if ("person".equals(node.getNodeName())) { 64 65 NodeList pChildNodes = node.getChildNodes(); 66 67 for (int t=0; t<pChildNodes.getLength(); t++) { 68 69 Node nd = pChildNodes.item(t); 70 71 if (nd.getNodeType() == Node.ELEMENT_NODE && nd.getNodeName().equals("user")) { 72 73 User user = new User(); 74 75 NodeList userChildNodes = nd.getChildNodes(); 76 77 for (int k=0; k<userChildNodes.getLength(); k++) { 78 Node userNode = userChildNodes.item(k); 79 String nodeName = userNode.getNodeName(); 80 String nodeValue = userNode.getTextContent(); 81 System.out.println("nodeType=" + userNode.getNodeType() + ", nodeName=" + nodeName + ", nodeValue=" + nodeValue); 82 83 84 if ("username".equals(nodeName)) 85 user.setUsername(nodeValue); 86 if ("password".equals(nodeName)) 87 user.setPassword(nodeValue); 88 if ("birthday".equals(nodeName)) 89 user.setBirthday(nodeValue); 90 } 91 list.add(user); 92 } // 若当前节点是user 93 } 94 } // 若当前元素是person的处理逻辑 95 }// 完成对根元素的所有子节点的判断 96 97 return list; 98 } 99 100 101 public static void main(String[] args) { 102 103 try { 104 DomUtil domUtil = new DomUtil(); 105 List<User> users = domUtil.parseXml("src/sax/parsing/user/jdbc-params.xml"); 106 107 for(User user : users) { 108 System.out.println(user); 109 } 110 } catch (ParserConfigurationException e) { 111 e.printStackTrace(); 112 } catch (Exception e) { 113 // TODO Auto-generated catch block 114 e.printStackTrace(); 115 } 116 } 117 } 输出结果:
nodeType=3, nodeName=#text, nodeValue= ###此处是Text节点的值(换行+3个制表符)
nodeType=1, nodeName=username, nodeValue=xzc
nodeType=3, nodeName=#text, nodeValue=
nodeType=1, nodeName=password, nodeValue=sdf23223
nodeType=3, nodeName=#text, nodeValue=
nodeType=1, nodeName=birthday, nodeValue=2012-01-23
nodeType=3, nodeName=#text, nodeValue=
nodeType=3, nodeName=#text, nodeValue=
nodeType=1, nodeName=username, nodeValue=误闯
nodeType=3, nodeName=#text, nodeValue=
nodeType=1, nodeName=password, nodeValue=wuchuang3223
nodeType=3, nodeName=#text, nodeValue=
nodeType=1, nodeName=birthday, nodeValue=2002-01-03
nodeType=3, nodeName=#text, nodeValue=
username = xzc, password = sdf23223, birthday = 2012-01-23
username = 误闯, password = wuchuang3223, birthday = 2002-01-03
采用SAX解析XML文件内容到User对象
1 package sax.parsing.user; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import javax.xml.parsers.ParserConfigurationException; 9 import javax.xml.parsers.SAXParser; 10 import javax.xml.parsers.SAXParserFactory; 11 12 import org.xml.sax.Attributes; 13 import org.xml.sax.SAXException; 14 import org.xml.sax.helpers.DefaultHandler; 15 16 public class SaxUtil extends DefaultHandler { 17 18 19 private List<User> users = new ArrayList<User>(); 20 private User user; 21 private String content; 22 23 @Override 24 public void characters(char [] ch, int start, int length) throws SAXException { 25 content = new String(ch, start, length); 26 } 27 28 /** 29 * xmlns:prefix=uri 30 * qName, prefix:localName 31 * @param uri 32 * The Namespace URI, or the empty string if the element has no Namespace URI 33 * or if Namespaceprocessing is not being performed. 34 * 如果元素没有命名空间URI、命名空间处理未被开启,则为空字符串 35 * @param localName 36 * The local name (without prefix), 37 * or the empty string if Namespace processing is not being performed. 38 * 不带前缀的本地名,如果命名空间处理未被开启,则为空字符串 39 * @param qName 40 * The qualified name (with prefix), 41 * or the empty string if qualified names are not available. 42 * 带前缀的全限定名,如果限定名不可得到,则为空串 43 * @param attributes 44 * The attributes attached to the element. 45 * If there are no attributes, it shall be an empty Attributes object. 46 * 附加在该元素上的属性,如果元素没有属性,则为空的Attributes对象 47 */ 48 @Override 49 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 50 51 if ("user".equals(localName)) { 52 user = new User(); 53 System.out.println("### " + localName); 54 System.out.println("<" + qName + ">"); 55 } 57 } 58 59 @Override 60 public void endElement(String uri, String localName, String qName) throws SAXException { 61 62 if ("username".equals(localName)) 63 user.setUsername(content); 64 65 if ("password".equals(localName)) 66 user.setPassword(content); 67 68 if ("birthday".equals(localName)) 69 user.setBirthday(content); 70 71 if ("user".equals(localName)) 72 users.add(user); 73 } 74 75 76 77 public List<User> getUsers() { 78 return users; 79 } 80 81 82 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { 83 84 SAXParserFactory parserFactory = SAXParserFactory.newInstance(); 85 parserFactory.setNamespaceAware(true); //设置启用命名空间,这样localName才可用 86 SAXParser parser = parserFactory.newSAXParser(); 87 88 SaxUtil saxUtil = new SaxUtil(); 89 90 parser.parse(new File("src/sax/parsing/user/jdbc-params.xml"), saxUtil); 91 List<User> userlist = saxUtil.getUsers(); 92 93 for (User user : userlist) 94 System.out.println(user); 95 } 96 97 } 输出结果:
### user
<u:user>
### user
<u:user>
username = xzc, password = sdf23223, birthday = 2012-01-23
username = 误闯, password = wuchuang3223, birthday = 2002-01-03
该实验例子摘自: http://toreking.iteye.com/blog/1669645