解析XML内容到User对象

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

时间: 2024-10-07 05:32:20

解析XML内容到User对象的相关文章

Dom4j解析xml内容——(三)

Dom4j取标签中的内容用 getText ,取开始标签和结束标签之间的值. 取属性值有两种方式: Jar包: XML原型: <?xml version="1.0" encoding="utf-8"?> <书架> <书> <书名>Java高级</书名> <作者>武陟县</作者> <价格>200元</价格> </书> <书> <书名

解析XML字符串为json对象

var overtime='<?xml version="1.0" encoding="UTF-8"?><response><code><liuhao>5555555</liuhao><age>555555555</age></code> <message>success</message> <totalCount>5000000<

C# xml压缩包不解压的情况下解析xml内容

1 string sourceFilePath = @"E:\文件拷贝\xx\3773\3773.zip"; 2 3 FileInfo fileInfo = new FileInfo(sourceFilePath); 4 long length = fileInfo.Length; 5 6 if (length == 0) 7 { 8 return; 9 } 10 11 using (ZipInputStream zip = new ZipInputStream(File.OpenRe

XStream解析XML文本并用反射机制转换为对象

xml文本格式是网络通信中最常用的格式,最近特别研究了一下如何解析xml文本并转换为对象,现在分享一下我最近的学习成果~ 先列一下本例中需要解析的xml文本: Xml代码   <results name="list"> <row pubtime="2016-04-13 16:40:13" author="APP"  id="140" title="什么是公告" content="

通过NSXMLParser来解析XML

NSXMLParser 使用 delegate 模型来解析 XML 内容的.下面我们来创建一个 XML 文 件,文件中包含如下内容(在工程中保存为 MyXML.xml): <?xml version="1.0" encoding="UTF-8"?> <root> <person id="1"> <firstName>zhang</firstName> <lastName>sa

Java解析XML文件的方式

在项目里,我们往往会把一些配置信息放到xml文件里,或者各部门间会通过xml文件来交换业务数据,所以有时候我们会遇到“解析xml文件”的需求.一般来讲,有基于DOM树和SAX的两种解析xml文件的方式,在这部分里,将分别给大家演示通过这两种方式解析xml文件的一般步骤. 1 XML的文件格式     XML是可扩展标记语言(Extensible Markup Language)的缩写,在其中,开始标签和结束标签必须配套地出现,我们来看下book.xml这个例子. 1 <?xml version=

SQLServer解析xml到Oracle

写了一个程序:根据状态位读取SQLserver 中的一张表,下载其中一个字段的值,这个值是XML类型的,然后把这个XML文件的内容插入到另一Oracle数据库,并更新SQLServer表的标志位,表示这条记录已经更新过. 我的思路是用java写个webservice,然后再用C#写个windows 服务每过30分钟运行一次.用java写业务是因为我觉得java操作oracle相对方便一点.用C#写windows服务是是因为我只知道能用C#写windows service,后台静默运行挺好. 看似

几个JQuery解析XML的程序例子

用JavaScript解析XML数据是常见的编程任务,JavaScript能做的,JQuery当然也能做.下面我们来总结几个使用JQuery解析XML的例子. 第一种方案:偃师市一中 <script type="text/javascript"> $(document).ready(function() { $.ajax({ url: 'http://www.nowamagic.net/cgi/test.xml', dataType: 'xml', success: fun

收藏几个JQuery解析XML的程序例子

用JavaScript解析XML数据是常见的编程任务,JavaScript能做的,JQuery当然也能做.下面我们来总结几个使用JQuery解析XML的例子. 第一种方案: <script type="text/javascript"> 博e百娱乐城$(document).ready(function() { $.ajax({ url: 'http://www.nowamagic.net/cgi/test.xml', dataType: 'xml', success: fu