1、 淮海工学院计算机工程学院 实验报告书 课 程 名: 《XML开发技术》 题 目: DOM解析 学 号: 姓 名: 评语: 成绩: 指导教师: 批阅时间: 年 月 日 《XM
2、L开发技术》实验报告 一、实验目的与要求 DOM(Document Object Model,文档对象模型)是W3C制定的一套规范标准,即规定了解析文件的接口 DOM规范的核心是树模型。对于解析XML文件的解析器,解析器通过读入XML文件在内存中建立一个树,也就是说XML文件的标记、标记的文本内容、实体等都会和内存中树的某个节点相对应。 1.掌握DO解析器的工作原理; 2.掌握节点的类型; 3.熟练掌握Element、Text、Document等节点的使用。 二、实验内容或题目 使用DOM解析器读取存储CD信息的XML文件,练习Element、Text、Document等节
3、点的使用。 三、实验步骤与源程序 1.使用以前创建的XML文件,文件中包含多条CD信息、图书信息等。 2.使用DOM,编写JAVA程序,读取XML文件中的数据,并显示到控制台上。 使用两种方法实现该功能: 1)使用getElementsByTagName()方法 2)使用getChildNodes()方法 3.属性值的读取使用两种 1)使用getAttribute方法 2)使用ATTR节点 //getChildNode.java import java.io.File; import javax.xml.parsers.DocumentBuilder; im
4、port javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class getChildNode { public static void main(String args[]) { try{ DocumentBuilderFactory factory = DocumentBuilderFactor
5、y.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File("Student.xml")); Element root = document.getDocumentElement(); String rootname = root.getNodeName(); System.out.println("XML文件根节点的名字:"+rootname); NodeList nodeL
6、ist = root.getChildNodes();
int size = nodeList.getLength();
for(int k =0; k 7、etAttribute("id");
String sex = elementNode.getAttribute("sex");
String content = elementNode.getTextContent();
System.out.print(name);
System.out.print(" id="+id);
System.out.println(" sex="+sex);
System.out.println(content); } } }
catch(Exception e){ Sys 8、tem.out .println(e); } }
}
//getElement.java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.do 9、m.Node;
import org.w3c.dom.NodeList;
public class Student {
public static void main(String args[])
{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder bulBuilder;
try {
bulBuilder = factory.newDocumentBuilder();
Document document = bulBuilder 10、parse(new File("Student.xml"));
Element root = document.getDocumentElement();
String rootname = root.getNodeName();
System.out .println(rootname);
NodeList nodeList = document.getElementsByTagName("学生");
int size = nodeList .getLength();
for(int k=0;k 11、node =nodeList.item(k);
String name = node.getNodeName();
NamedNodeMap map = node.getAttributes();
String content = node.getTextContent();
System.out.print(name);
for(int i=0;i 12、tName();
String attValue = attrNode.getValue();
System.out.print(" "+attName+"="+attValue+" "); }
System.out .print(content); }
} catch (Exception e) {
e.printStackTrace();} }
4. 阅读并调试如下代码,要求读懂程序。






