现有XML文件:scores.xml,其内容为:
<?xml version="1.0" encoding="UTF-8"?>
<!--声明内部DTD-->
<!DOCTYPE scores[
<!ELEMENT scores (student+)>
<!ELEMENT student (name,course,score)>
<!ATTLIST student id CDATA #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT course (#PCDATA)>
<!ELEMENT score (#PCDATA)>
]>
<scores>
<student id="1">
<name>张三</name>
<course>JAVA</course>
<score>89</score>
</student>
<student id="2">
<name>李四</name>
<course>sql</course>
<score>58</score>
</student>
<student id="3">
<name>王唯一</name>
<course>C++</course>
<score>88</score>
</student>
</scores>
利用dom4j读取xml文件内容:
public static void main(String[] args) throws Exception {
//[1]创建SAXReader对象,用于读取XML文件
SAXReader reader = new SAXReader();
//[2]读取XML文件,得到Document对象:此对象即为XML文件
Document doc = reader.read(new File("src/scores.xml"));
//[3]获取根元素
Element root = doc.getRootElement();
//[4]获取根元素下的所有子元素,迭代器类型可为Element,或者为?,使用?时,取出元素要进行强转
Iterator<?> it = root.elementIterator();
while(it.hasNext()) {
//取出元素
Element e = (Element)it.next();
System.out.println(e.getName()); //打印元素名
//获取该元素的属性:id
Attribute id = e.attribute(0);
System.out.println(id.getName()+"="+id.getValue());
//获取student子元素
Element name = e.element("name");
Element course = e.element("course");
Element score = e.element("score");
System.out.println(name.getName()+" = "+name.getStringValue());
System.out.println(course.getName()+" = "+course.getText());
System.out.println(score.getName()+" = "+score.getStringValue());
System.out.println("---------------------------");
}
}