users.xml
<?xml version="1.0" encoding="UTF-8"?> <xml-root>
<conn-params>
<conn-url>jdbc:mysql://192.168.101.7:3306/bbs</conn-url>
<conn-driver>com.mysql.jdbc.Driver</conn-driver>
<conn-username>root</conn-username>
<conn-password>root</conn-password>
</conn-params> <person xmlns:u="http://example.org/user">
<u:user>
<u:username>xzc</u:username>
<u:password>sdf23223</u:password>
<u:birthday>2012-01-23</u:birthday>
</u:user>
<u:user>
<u:username>误闯</u:username>
<u:password>wuchuang3223</u:password>
<u:birthday>2002-01-03</u:birthday>
</u:user>
</person>
</xml-root>
采用DOM api 解析XML
1. User类
public class User { private String username;
private String password;
private String birthday; public String toString() {
return "username = " + username + ", password = " + password + ", birthday = " + birthday;
} //省略setter,getter
}
2. DomUtil解析类
package sax.parsing.user; import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource; public class DomUtil { private DocumentBuilderFactory builderFactory;
private DocumentBuilder builder;
private Document document; public DomUtil() throws ParserConfigurationException {
builderFactory = DocumentBuilderFactory.newInstance();
builder = builderFactory.newDocumentBuilder();
} public DocumentBuilderFactory getBuilderFactory() {
return builderFactory;
}
public DocumentBuilder getBuilder() {
return builder;
} public List<User> parseXml(String filepath) throws Exception { document = builder.parse(new InputSource(new FileInputStream(filepath))); List<User> list = new ArrayList<User>(); Element root = document.getDocumentElement(); //从文档根节点获取文档根元素节点root => xml
NodeList childNodes = root.getChildNodes(); for (int i=0; i<childNodes.getLength(); i++) {
Node node = childNodes.item(i); /*
* <person>
<user>
<username>xzc</username>
<password>sdf23223</password>
<birthday>2012-01-23</birthday>
</user>
<user>
<username>误闯</username>
<password>wuchuang3223</password>
<birthday>2002-01-03</birthday>
</user>
</person>
*/
if ("person".equals(node.getNodeName())) { NodeList pChildNodes = node.getChildNodes(); for (int t=0; t<pChildNodes.getLength(); t++) { Node nd = pChildNodes.item(t); if (nd.getNodeType() == Node.ELEMENT_NODE && nd.getNodeName().equals("user")) { User user = new User(); NodeList userChildNodes = nd.getChildNodes(); for (int k=0; k<userChildNodes.getLength(); k++) {
Node userNode = userChildNodes.item(k);
String nodeName = userNode.getNodeName();
String nodeValue = userNode.getTextContent();
System.out.println("nodeType=" + userNode.getNodeType() + ", nodeName=" + nodeName + ", nodeValue=" + nodeValue); if ("username".equals(nodeName))
user.setUsername(nodeValue);
if ("password".equals(nodeName))
user.setPassword(nodeValue);
if ("birthday".equals(nodeName))
user.setBirthday(nodeValue);
}
list.add(user);
} // 若当前节点是user
}
} // 若当前元素是person的处理逻辑
}// 完成对根元素的所有子节点的判断 return list;
} public static void main(String[] args) { try {
DomUtil domUtil = new DomUtil();
List<User> users = domUtil.parseXml("src/sax/parsing/user/jdbc-params.xml"); for(User user : users) {
System.out.println(user);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} 输出结果:
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对象
package sax.parsing.user; import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; 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 SaxUtil extends DefaultHandler { private List<User> users = new ArrayList<User>();
private User user;
private String content; @Override
public void characters(char [] ch, int start, int length) throws SAXException {
content = new String(ch, start, length);
} /**
* xmlns:prefix=uri
* qName, prefix:localName
* @param uri
* The Namespace URI, or the empty string if the element has no Namespace URI
* or if Namespaceprocessing is not being performed.
* 如果元素没有命名空间URI、命名空间处理未被开启,则为空字符串
* @param localName
* The local name (without prefix),
* or the empty string if Namespace processing is not being performed.
* 不带前缀的本地名,如果命名空间处理未被开启,则为空字符串
* @param qName
* The qualified name (with prefix),
* or the empty string if qualified names are not available.
* 带前缀的全限定名,如果限定名不可得到,则为空串
* @param attributes
* The attributes attached to the element.
* If there are no attributes, it shall be an empty Attributes object.
* 附加在该元素上的属性,如果元素没有属性,则为空的Attributes对象
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("user".equals(localName)) {
user = new User();
System.out.println("### " + localName);
System.out.println("<" + qName + ">");
}
} @Override
public void endElement(String uri, String localName, String qName) throws SAXException { if ("username".equals(localName))
user.setUsername(content); if ("password".equals(localName))
user.setPassword(content); if ("birthday".equals(localName))
user.setBirthday(content); if ("user".equals(localName))
users.add(user);
} public List<User> getUsers() {
return users;
} public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setNamespaceAware(true); //设置启用命名空间,这样localName才可用
SAXParser parser = parserFactory.newSAXParser(); SaxUtil saxUtil = new SaxUtil(); parser.parse(new File("src/sax/parsing/user/jdbc-params.xml"), saxUtil);
List<User> userlist = saxUtil.getUsers(); for (User user : userlist)
System.out.println(user);
} } 输出结果:
### 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