<?xml version="1.0" encoding="UTF-8"?><!-- xml中的dtd规则 --><!DOCTYPE students [<!ELEMENT student (id,name,age,score)><!ELEMENT id (#PCDATA)><!ELEMENT name (#PCDATA)><!ELEMENT age (#PCDATA)><!ELEMENT score (#PCDATA)>]><students><student><id></id><name></name><age></age><score></score></student></students>
XML的DTD详情
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE TVSCHEDULE [<!--电视节目表DTD David Moisan创造--><!ELEMENT TVSCHEDULE (CHANNEL+)><!ELEMENT CHANNEL (BANNER,DAY+)><!ELEMENT BANNER (#PCDATA)><!ELEMENT DAY (DATE,(HOLIDAY|PROGRAMSLOT+)+)><!ELEMENT HOLIDAY (#PCDATA)><!ELEMENT DATE (#PCDATA)><!ELEMENT PROGRAMSLOT (TIME,TITLE,DESCRIPTION?)><!ELEMENT TIME (#PCDATA)><!ELEMENT TITLE (#PCDATA)><!ELEMENT DESCRIPTION (#PCDATA)><!ATTLIST TVSCHEDULE NAME CDATA #REQUIRED><!ATTLIST CHANNEL CHAN CDATA #REQUIRED><!ATTLIST PROGRAMSLOT VTR CDATA #IMPLIED><!ATTLIST TITLE RATING CDATA #IMPLIED><!ATTLIST TITLE LANGUAGE CDATA #IMPLIED>
XML的DTD.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE TVSCHEDULE SYSTEM "TVSCHEDULE.dtd"><!--电视节目表DTD David Moisan创造--><!ELEMENT TVSCHEDULE (CHANNEL+)><!ELEMENT CHANNEL (BANNER,DAY+)><!ELEMENT BANNER (#PCDATA)><!ELEMENT DAY (DATE,(HOLIDAY|PROGRAMSLOT+)+)><!ELEMENT HOLIDAY (#PCDATA)><!ELEMENT DATE (#PCDATA)><!ELEMENT PROGRAMSLOT (TIME,TITLE,DESCRIPTION?)><!ELEMENT TIME (#PCDATA)><!ELEMENT TITLE (#PCDATA)><!ELEMENT DESCRIPTION (#PCDATA)><!ATTLIST TVSCHEDULE NAME CDATA #REQUIRED><!ATTLIST CHANNEL CHAN CDATA #REQUIRED><!ATTLIST PROGRAMSLOT VTR CDATA #IMPLIED><!ATTLIST TITLE RATING CDATA #IMPLIED><!ATTLIST TITLE LANGUAGE CDATA #IMPLIED><TVSCHEDULES><TVSCHEDULE NAME="1"><CHANNEL CHAN="1"><BANNER></BANNER><DAY><DATE></DATE><HOLIDAY></HOLIDAY></DAY></CHANNEL></TVSCHEDULE><TVSCHEDULE NAME="1"><CHANNEL CHAN="1"><BANNER></BANNER><DAY><DATE></DATE><PROGRAMSLOT VTR=""><TIME RATING=""></TIME><TITLE LANGUAGE=""></TITLE><DESCRIPTION></DESCRIPTION></PROGRAMSLOT><HOLIDAY></HOLIDAY></DAY></CHANNEL></TVSCHEDULE></TVSCHEDULES>
XML的Test解析代码(dom4j)
package com.ddh.test;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.junit.Test;publicclassXMLTest{@TestpublicvoidtestDOM4j()throws DocumentException {/*
* 早起JDK为我们提供了两种xml解析技术Dom和Sax简介(已经过时)
*
* 第三方解析技术: dom4j解析技术
*
* 导入dom4j jar包到lib文件夹,鼠标右键build path-->add to
*///1 创建SAXReader对象 reader
SAXReader reader=newSAXReader();//2 reader对象关联指定的xml文件 创建Document
Document document=reader.read("src\\person.xml");//3 获取根节点
Element root=document.getRootElement();//4 通过根节点获取子节点@SuppressWarnings("unchecked")//取消警告
List<Element> personList = root.elements("person");//5遍历子节点并输出for(Element person : personList){//获取子节点的属性
String id = person.attributeValue("id");//获取子节点的内容
Element nameElement = person.element("name");
Element ageElement = person.element("age");
Element scoreElement = person.element("score");
System.out.println(id+" "+nameElement.getText()+" "+ageElement.getText()+" "+scoreElement.getText());}}}