Java 之 XML
1.XML
a.定义:可扩展标记语言
b.用途:现在主要用来以一种格式化的形式来存储数据
c.注意:XML中是区分大小写的
2.DTD
a.定义:文档类型定义
b.作用:定义 XML 文档的合法构建模块
c.语法:
<?xml version="1.0" encoding="utf-8"?> <!-- DTD语句 --> <!DOCTYPE students [ <!ELEMENT students (student*,teacher)> <!ELEMENT student (#PCDATA)> <!ELEMENT teacher (#PCDATA)> ]> <!-- XML语句 --> <students> <student></student> <student></student> <teacher></teacher> </students>
d.外部引用DTD:
<!DOCTYPE 根元素 SYSTEM "文件名"> SYSTEM表示的是本地的DTD文件,PUBLIC表示的是官方的DTD文件
<!DOCTYPE students SYSTEM "myDTD.dtd">
3.XML解析器
a.分类:
①DOM(树结构):整个文档必须在内存解析和储存,因此对大型文档来说,耗内存,占用资源严重; 也因为数据都在内存,解析获取数据效率高
②SAX():基于事件驱动的模型,标签一个一个的解析,开始标签和结束标签对应不同的事件,不会将整个文档加载到内存,所以不会浪费内存资源; 也因此解析获取
数据效率不高
b.解析:
File file = new File("src/com/jiexi/my.xml"); SAXReader read = new SAXReader(); try { Document doc = read.read(file); Element e = doc.getRootElement(); List<Element> stus = e.elements("student"); List<Student> list = new ArrayList<Student>(); for(Element stu : stus){ Student s = new Student(); Attribute a = stu.attribute("id"); System.out.println(a.getValue()); s.setName(stu.element("name").getText().trim()); s.setAge(Integer.parseInt(stu.element("age").getText().trim())); list.add(s); } for(Student s : list){ System.out.println("name:"+s.getName()); System.out.println("age:"+s.getAge()); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
c.写:
File file = new File("D:/134xml.xml"); OutputStream out = new FileOutputStream(file); XMLWriter xmlWriter = new XMLWriter(out); Document doc = DocumentHelper.createDocument(); Element e = doc.addElement("users"); Element user = e.addElement("user"); user.addAttribute("id", "1"); user.addElement("userName").setText("zhangsan"); try { xmlWriter.write(doc); xmlWriter.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }