<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hr[
<!ELEMENT hr (employee+ | boss+)>
<!ELEMENT employee (name,age,sex)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT sex (#PCDATA)>
<!ELEMENT boss (name1,age1)>
<!ELEMENT name1 (#PCDATA)>
<!ELEMENT age1 (#PCDATA)>
<!ENTITY name "蒋映辉">
]>
<!-- 注意 用|选择的时候,两者只能使用一个 -->
<hr>
<employee>
<name >&name;</name>
<age>25</age>
<sex>male</sex>
</employee>
<employee>
<name>huazehui</name>
<age>25</age>
<sex>male</sex>
</employee>
</hr>
首先,就是编码问题了,方老师讲得好,windos用的是GB2312编码,所以如果用记事本编的话,储存的时候要储存为UTF-8的
然后是dtd的格式问题,代码上
读取xml
package com.test1;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* 这是读取XML的实例
* @author Administrator
*
*/
public class Demo1 {
//得到一个节点,并输出其中的节点及内容
public void test1() throws Exception{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); //建立工厂
DocumentBuilder bulider=dbf.newDocumentBuilder(); //得到DOM解析器
Document document=bulider.parse("src/T2.XML");//解析xml文档
Node node=document.getElementsByTagName("书").item(0);
NodeList list=node.getChildNodes();
for(int i=0;i<list.getLength();i++){
Node n=list.item(i);
if(n instanceof Element) //element是标签 node是节点,就可能是中间的空格回车
System.out.println(n.getNodeName()+":"+n.getTextContent());
}
String name=node.getTextContent();
//System.out.println();
}
//遍历父节点,并获取其各节点的名称 这里无法遍历内容,因为遍历书架的时候,它会把里边所有内容全部当做它的类容
@Test
public void test2() throws Exception{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); //建立工厂
DocumentBuilder bulider=dbf.newDocumentBuilder(); //得到DOM解析器
Document document=bulider.parse("src/T2.XML");//解析xml文档
Node node=document.getElementsByTagName("书架").item(0);
read(node);
}
private void read(Node node) {
// TODO 用递归方法遍历整个node
NodeList list=node.getChildNodes();
if(node instanceof Element) {
System.out.println(node.getNodeName()+":");
if(node.getNodeName().equals("书名")) System.out.println(node.getTextContent());
}
for(int i=0;i<list.getLength();i++){
read(list.item(i));
}
}
//得到标签中的内容 <书名 版本="第三版">JSP</书名>
//得到一个节点,并输出其中的节点及内容
public void test3() throws Exception{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); //建立工厂
DocumentBuilder bulider=dbf.newDocumentBuilder(); //得到DOM解析器
Document document=bulider.parse("src/T2.XML");//解析xml文档
Node node=document.getElementsByTagName("书名").item(0);
Element element =(Element) node;
String value=element.getAttribute("版本");
System.out.println(value);
}
}