xml提供一套跨平台, 跨网络,跨程序的数据描述语言,使用xml可以方便的实现数据交换,系统配置,内容管理等常见功能。
基本格式
studeng,name,sex,age为元素节点
id="001"为属性节点
张三 为文本节点
<?xml version="1.0" encoding="UTF-8"?>
<student>
<name id="001">张三</name>
<sex>男</sex>
<age>20</age>
</student>
DOM方式解析XML
把整个XML文档加载到内存,转化为DOM树,应用程序可以随机访问DOM树的任何数据
优点灵活性强,速度快
缺点 消耗资源比较多
文档构建工厂
factory单例方式获取实例
newDocumentBuilder 文档构建模型
parse解析配置获取xml文档
getElementsByTagName通过标签名字获取dom节点
nodeList.item(0)获取第一个<student>...</student>元素
getFirstChild 获取第一个子节点 张三 getNodeValue获取值
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public static void main(String[] args) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("src/student.xml");
NodeList nodeList=doc.getElementsByTagName("student");
Element e=(Element)nodeList.item(0);
System.out.println("姓名:"+e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
System.out.println("性别:"+e.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue());
System.out.println("年龄:"+e.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
解析属性
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="001">
<name>张三</name>
<sex>男</sex>
<age>20</age>
</student>
<student id="002">
<name>李四</name>
<sex>女</sex>
<age>21</age>
</student>
</students>
getAttributes 获取node节点的所有属性
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public static void printNodeAttr(Node node){
NamedNodeMap namedNodeMap=node.getAttributes();
for(int i=0;i<namedNodeMap.getLength();i++){
Node attrNode=namedNodeMap.item(i);
System.out.println(attrNode.getNodeName()+":"+attrNode.getFirstChild().getNodeValue());
}
}
public static void main(String[] args) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("src/students.xml");
NodeList nodeList=doc.getElementsByTagName("students");
Element element=(Element)nodeList.item(0);
NodeList studentsNodeList=element.getElementsByTagName("student");
for(int i=0;i<studentsNodeList.getLength();i++){
Element e=(Element)studentsNodeList.item(i);
System.out.println("姓名:"+e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
printNodeAttr(e.getElementsByTagName("name").item(0));
System.out.println("性别:"+e.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue());
System.out.println("年龄:"+e.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());
System.out.println("================");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SAX方式解析XML
SAX对文档进行顺序扫描,扫描文档的开始与结束,元素的开始于结束,通知事件处理函数,由事件处理函数做相应的动作。
优点 消耗资源少,适合大文件解析
缺点 只能读取不能修改,开发复杂
定义事件
startDocument 文档开始时候的事件
startElement 元素开始事件 元素是节点的一个子集
endElement 元素扫描完事件
characters 文本节点事件
SAXParserFactory 获取工厂,解析工厂
newSAXParser 获取解析器
qName 所有元素 attributes所有属性 attributes.getQName(i)属性的名字
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 SAX extends DefaultHandler{
@Override
public void startDocument() throws SAXException {
System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
@Override
public void endDocument() throws SAXException {
System.out.print("\n 扫描文档结束");
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.print("<");
System.out.print(qName);
if(attributes!=null){
for(int i=0;i<attributes.getLength();i++){
System.out.print(" "+attributes.getQName(i)+"=\""+attributes.getValue(i)+"\"");
}
}
System.out.print(">");
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.print("</");
System.out.print(qName);
System.out.print(">");
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.print(new String(ch,start,length));
}
public static void main(String[] args) throws Exception{
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
parser.parse("src/student.xml", new SAX());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="001">
<name>张三</name>
<sex>男</sex>
<age>20</age>
</student>
<student id="002">
<name>李四</name>
<sex>女</sex>
<age>21</age>
</student>
</students>
import java.util.ArrayList;
import java.util.List;
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;
import com.java1234.model.Student;
public class SAX extends DefaultHandler{
private List<Student> students=null;
private Student student=null;
private String preTag=null; // 标记上一个节点名称
@Override
public void startDocument() throws SAXException {
System.out.println("开始读取学生信息");
students=new ArrayList<Student>();
}
@Override
public void endDocument() throws SAXException {
System.out.println("\n 学生信息读取完毕");
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if("student".equals(qName)){
student=new Student();
student.setId(attributes.getValue(0));//获取对象放到集合中
}
preTag=qName;
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("student".equals(qName)){
students.add(student);
student=null;
}
preTag=null;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(preTag!=null){
String content=new String(ch,start,length);
if("name".equals(preTag)){
student.setName(content);
}else if("sex".equals(preTag)){
student.setSex(content);
}else if("age".equals(preTag)){
student.setAge(Integer.parseInt(content));
}
}
}
public static void main(String[] args) throws Exception{
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
SAX sax=new SAX();
parser.parse("src/students.xml", sax);
for(Student s:sax.students){
System.out.println(s);
}
}
}
JDOM和DOM4j解析XML
JDOM生成XML
<?xml version="1.0" encoding="UTF-8"?>
<student id="001" aa="xx">
<name>张三</name>
<sex>男</sex>
<age>20</age>
</student>
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
public class JDOM {
public static void main(String[] args) {
Element student=new Element("student");
Attribute id=new Attribute("id", "001");
Attribute aa=new Attribute("aa", "xx");
student.setAttribute(id);
student.setAttribute(aa);
Element name=new Element("name");
name.setText("张三");
student.addContent(name);
Element sex=new Element("sex");
sex.setText("男");
student.addContent(sex);
Element age=new Element("age");
age.setText("20");
student.addContent(age);
Document document=new Document(student);//根节点
XMLOutputter out=new XMLOutputter();//xml输出器
out.setFormat(out.getFormat().setEncoding("UTF-8"));
try {
out.output(document, new FileOutputStream("src/student2.xml"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JDOM遍历XML
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="001">
<name>张三</name>
<sex>男</sex>
<age>20</age>
</student>
<student id="002">
<name>李四</name>
<sex>女</sex>
<age>21</age>
</student>
</students>
SAXBuilder()构建文本
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
public class JDOM {
public static void main(String[] args) throws Exception{
SAXBuilder builder=new SAXBuilder();
Document document=builder.build("src/students.xml");
Element students=document.getRootElement();
List studentList=students.getChildren("student");
for(int i=0;i<studentList.size();i++){
Element student=(Element)studentList.get(i);
String id=student.getAttributeValue("id");
String name=student.getChildText("name");
String sex=student.getChildText("sex");
String age=student.getChildText("age");
System.out.println("学号:"+id+";姓名:"+name+";性别:"+sex+";年龄:"+age);
}
}
}
DOM4J生成XML
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class DOM4J {
public static void main(String[] args) {
Document document=DocumentHelper.createDocument();
Element studentElement=document.addElement("student");
studentElement.addAttribute("id", "001");
studentElement.addAttribute("aa", "xx");
Element name=studentElement.addElement("name");
name.setText("张三");
Element sex=studentElement.addElement("sex");
sex.setText("男");
Element age=studentElement.addElement("age");
age.setText("20");
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
try {
XMLWriter writer=new XMLWriter(new FileOutputStream("src/student3.xml"),format);
writer.write(document);
writer.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
DOM4J解析XML
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class DOM4J {
public static void main(String[] args) throws Exception{
SAXReader saxReader=new SAXReader();
Document document=saxReader.read("src/students.xml");
Element rootElement=document.getRootElement();
Iterator iter=rootElement.elementIterator();
while(iter.hasNext()){
Element studentElement=(Element)iter.next();
System.out.println("学号:"+studentElement.attributeValue("id"));
System.out.println("姓名:"+studentElement.elementText("name"));
System.out.println("性别:"+studentElement.elementText("sex"));
System.out.println("年龄:"+studentElement.elementText("age"));
System.out.println("=========");
}
}
}