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

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

  1. Dom4j解析xml内容——(三)

    Dom4j取标签中的内容用 getText ,取开始标签和结束标签之间的值. 取属性值有两种方式:

  2. 解析XML字符串为json对象

    var overtime='<?xml version="1.0" encoding="UTF-8"?><response><co ...

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

    string sourceFilePath = @"E:\文件拷贝\xx\3773\3773.zip"; FileInfo fileInfo = new FileInfo(sour ...

  4. 用js(JavaScript-jQuery)解析XML文件 无法成功 获得XML对象,字符串一些心得

    原文作者:aircraft 原文地址:https://www.cnblogs.com/DOMLX/p/7822962.html 解析XML文件遇到的问题 今天秦博士叫我解析一下XML文件,将里面的所有 ...

  5. Android解析xml文件-采用DOM,PULL,SAX三种方法解析

    解析如下xml文件 <?xml version="1.0" encoding="UTF-8"?> <persons> <perso ...

  6. 用js解析XML文件,字符串一些心得

    解析XML文件遇到的问题 今天秦博士叫我解析一下XML文件,将里面的所有的X坐标Y坐标放在一个数组里面然后写在文档里让他进行算法比对,大家都知道了啦,解析XML文件获取里面的坐标数据什么的,当然是用前 ...

  7. Java高级特性 第13节 解析XML文档(1) - DOM和XPath技术

    一.使用DOM解析XML文档 DOM的全称是Document Object Model,也即文档对象模型.在应用程序中,基于DOM的XML分析器将一个XML文档转换成一个对象模型的集合(通常称DOM树 ...

  8. XML概念定义以及如何定义xml文件编写约束条件java解析xml DTD XML Schema JAXP java xml解析 dom4j 解析 xpath dom sax

    本文主要涉及:xml概念描述,xml的约束文件,dtd,xsd文件的定义使用,如何在xml中引用xsd文件,如何使用java解析xml,解析xml方式dom sax,dom4j解析xml文件 XML来 ...

  9. python开发_xml.dom_解析XML文档_完整版_博主推荐

    在阅读之前,你需要了解一些xml.dom的一些理论知识,在这里你可以对xml.dom有一定的了解,如果你阅读完之后. 下面是我做的demo 运行效果: 解析的XML文件位置:c:\\test\\hon ...

随机推荐

  1. iOS开发中WiFi相关功能总结

    http://www.cocoachina.com/ios/20160715/17022.html 投稿文章,作者:Haley_Wong(简书) 查漏补缺集是自己曾经做过相关的功能,但是重做相关功能或 ...

  2. day39-Spring 13-Spring的JDBC模板:默认连接池的配置

    Spring内置的连接池DriverManagerDataSource的源码. /* * Copyright 2002-2008 the original author or authors. * * ...

  3. JavaScript--for in循环访问属性用"."和[ ]的区别

    // for in 循环遍历对象的时候// 内部要访问属性的时候不能点语法访问,因为for in 的key是字符串格式// 可通过方括号实现访问 for(var key in manObj) { co ...

  4. Android实战:手把手实现“捧腹网”APP(三)-----UI实现,逻辑实现

    Android实战:手把手实现"捧腹网"APP(一)-–捧腹网网页分析.数据获取 Android实战:手把手实现"捧腹网"APP(二)-–捧腹APP原型设计.实 ...

  5. vagrant 安装 ubuntu

    安装版本: ubuntu  trusty64(14.04) step1: 安装vagrant,vbox step2: 下载box文件(官网http://www.vagrantbox.es/) http ...

  6. Python学习之路5☞文件处理

    一.文件处理流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 正趣果上果 Interesting fruit fruit 词:郭婞 曲:陈粒 编曲/混音/和声:燕池 萧: ...

  7. 【LINUX】降级安装低版本GCC,G++

    由于要制作crosstool,需要用到gcc 4.1.2来编译,而Ubuntu 12.04下的gcc版本是gcc 4.6.3,高版本的gcc也不是好事啊. 下面介绍gcc 4.1.2的编译安装方法: ...

  8. [牛腩]如何关闭.net framework4.0的请求验证 标签: 发布 2015-07-31 09:27 887人阅读 评论(38)

    敲牛腩的时候,点击运行提示:从客户端中检测到有潜在危险的 Request.Form 值,感觉自己代码敲的并没有问题,于是开始各种查,下面分享一下我对此进行的研究. 为什么会报这个错误? 在 Web 应 ...

  9. 阿里云智能数据构建与管理 Dataphin公测,助力企业数据中台建设

    阿里云智能数据构建与管理 Dataphin (下简称“Dataphin”)近日重磅上线公共云,开启智能研发版本的公共云公测!在此之前,Dataphin以独立部署方式输出并服务线下客户,已助力多家大型客 ...

  10. 洞见数据库前沿 阿里云数据库最强阵容 DTCC 2019 八大亮点抢先看

    摘要: 作为DTCC的老朋友和全球领先的云计算厂商,阿里云数据库团队受邀参加本次技术盛会,不仅将派出重量级嘉宾阵容,还会为广大数据库业内人士和行业用户奉上8场精彩议题.下面小编就为大家提前梳理了8大亮 ...