XML:(eXtensible Markup Language)
可扩展标记语言
是一种数据格式,用于存储和传输数据
声明一个xml文件
<?xml version="1.0" encoding="UTF-8" ?>
文档类型定义
<!DOCTYPE note SYSTEM “book.dtd”>
only:有且只有一个跟节点
一个例子
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
特殊字符
在 XML 中,有 5 个预定义的实体引用:
格式验证
浏览器打开不报错,就ok
Java的XML解析的3个方法:
1.DOM(Document Object Model)
文档对象模型
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="findUserById" parameterType="int" resultType="com.lucas.javase.mybatis.introduction.po.User" >
SELECT * FROM user WHERE id = #{id}
</select>
<select id="findUserListByName" parameterType="string" resultType="com.lucas.javase.mybatis.introduction.po.User">
SELECT * FROM user WHERE username LIKE '%${value}%'
</select>
<insert id="insertUser" parameterType="com.lucas.javase.mybatis.introduction.po.User" useGeneratedKeys="true">
INSERT INTO user (username,sex,birthday,address) VALUES (#{username},#{sex},#{birthday},#{address})
</insert>
</mapper>
Dom.java
static String uri="UserMapper.xml";
public static void dom() throws ParserConfigurationException, SAXException, IOException{
//DocumentBuilderFactory是抽象类,不能实例化new
DocumentBuilderFactory instance = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = instance.newDocumentBuilder(); Document document = builder.parse(uri);
print(document,0);
} private static void print(Node document, int i) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
switch (document.getNodeType()) {
case Node.DOCUMENT_NODE:
System.out.println("DOCUMENT_NODE: "+document.getNodeName());
break;
case Node.ELEMENT_NODE:
System.out.println("ELEMENT_NODE: "+document.getNodeName());
break;
case Node.TEXT_NODE:
System.out.println("TEXT_NODE: "+document.getNodeName()+"="+document.getNodeValue());
break;
case Node.ATTRIBUTE_NODE:
System.out.println("ATTRIBUTE_NODE: "+document.getNodeName()+"="+document.getNodeValue());
break;
case Node.CDATA_SECTION_NODE:
System.out.println("CDATA_SECTION_NODE: "+document.getNodeName()+"="+document.getNodeValue());
break;
case Node.COMMENT_NODE:
System.out.println("COMMENT_NODE: "+document.getNodeName()+"="+document.getNodeValue());
break;
default:
System.out.println("NODETYPE:"+document.getNodeType()+",NODEVALUE:"+document.getNodeValue());
break;
}
for (Node child = document.getFirstChild(); child !=null; child=child.getNextSibling()) {
print(child,i+1);
}
}
输出
DOCUMENT_NODE: #document
NODETYPE:10,NODEVALUE:null
ELEMENT_NODE: mapper
TEXT_NODE: #text= ELEMENT_NODE: select
TEXT_NODE: #text=
SELECT * FROM user WHERE id = #{id} TEXT_NODE: #text= ELEMENT_NODE: select
TEXT_NODE: #text=
SELECT * FROM user WHERE username LIKE '%${value}%' TEXT_NODE: #text= ELEMENT_NODE: insert
TEXT_NODE: #text=
INSERT INTO user (username,sex,birthday,address) VALUES (#{username},#{sex},#{birthday},#{address}) TEXT_NODE: #text=
缺点是:一次性加载整个dom,占用内存大,速度慢
2、SAX(Simple API for XML)
XML的简单接口
Sax.java
public static void sax() throws ParserConfigurationException, SAXException, IOException{
//SAXParserFactory也是抽象类
SAXParserFactory instance = SAXParserFactory.newInstance();
SAXParser saxParser = instance.newSAXParser();
saxParser.parse(uri, new SaxHandler());
}
SaxHandler.java
public class SaxHandler extends DefaultHandler{ void print(Object...objects){
for (Object object : objects) {
System.out.print(object);
System.out.print(" ");
}
}
@Override
public void startDocument() throws SAXException {
System.out.println("startDocument");
} @Override
public void endDocument() throws SAXException {
System.out.println("endDocument");
} @Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("startElement "+localName+" "+qName);
} @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("endElement "+localName+" "+qName);
} @Override
public void characters(char[] ch, int start, int length) throws SAXException {
System.out.println("characters "+new String(ch,start,length));
} @Override
public void error(SAXParseException e) throws SAXException {
print("error:",e);
} }
输出
startDocument
startElement mapper
startElement select
characters
SELECT * FROM user WHERE id = #{id} endElement select
startElement select
characters
SELECT * FROM user WHERE username LIKE '%${value}%' endElement select
startElement insert
characters
INSERT INTO user (username,sex,birthday,address) VALUES (#{username},#{sex},#{birthday},#{address}) endElement insert
endElement mapper
endDocument
流式读取dom,占用内存小,速度快,基于事件,使用事件回调处理dom
3、Jackson
这个一个开源XML工具
引入依赖包,maven的pom.xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.woodstox</groupId>
<artifactId>woodstox-core</artifactId>
<version>5.1.0</version>
</dependency>
需要序列化的类
User.java
public class User {
private int id;
private String username;
private String sex;
private String birthday;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + "]";
}
public User() {
}
public User(int id, String username, String sex, String birthday, String address) {
super();
this.id = id;
this.username = username;
this.sex = sex;
this.birthday = birthday;
this.address = address;
}
}
Jackson.java
public class Jackson { public static void main(String[] args) {
try {
//jacksonBean2XML();
jacksonXML2Bean();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* POJO 转为XML
*
* @throws JsonProcessingException
*/
public static void jacksonBean2XML() throws JsonProcessingException{
// JacksonXmlModule module = new JacksonXmlModule();
// module.setDefaultUseWrapper(false); XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setDefaultUseWrapper(false);
User user=new User(1,"lucas","nan","2019-10-01","上海");
String xml=xmlMapper.writeValueAsString(user);
System.out.println(xml);
} public static void jacksonXML2Bean() throws JsonParseException, JsonMappingException, IOException{
// JacksonXmlModule module = new JacksonXmlModule();
// module.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setDefaultUseWrapper(false);
//自动忽略无法对应pojo的字段
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
User user=xmlMapper.readValue("<User><id>1</id><username>lucas</username><sex>nan</sex><birthday>2019-10-01</birthday><address>上海</address></User>", User.class);
System.out.println(user);
} }
使用第三方的工具,更加方便,面向对象开发。