<%--List8_11_1.jsp--%>
<%@ page import="javax.xml.parsers.DocumentBuilder,
                 javax.xml.parsers.DocumentBuilderFactory,
                 org.w3c.dom.*,
                 java.io.*,
                 org.apache.xml.serialize.XMLSerializer,
                 org.apache.xml.serialize.OutputFormat"%>
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<html>
  <head><title>DOM读取XML文档</title></head>
  <body>
    <%
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setIgnoringElementContentWhitespace(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc=db.parse(pageContext.getServletContext().getResourceAsStream("/student.xml"));
        NodeList students=doc.getElementsByTagName("student");
        NodeList names=doc.getElementsByTagName("name");
        out.println("There are "+students.getLength()+" students:<br/>");
        for(int i=0;i<students.getLength();i++)
        {
            //输出每个学生的名字
            out.println(names.item(i).getFirstChild().getNodeValue()+"<br/>");
            //将学生王五的名字改为王小五
            if(names.item(i).getFirstChild().getNodeValue().equals("王五"))
            names.item(i).getFirstChild().setNodeValue("王小五");
        }
        //将DOM树保存到student2.xml文件中
        OutputFormat format = new OutputFormat(doc);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        XMLSerializer serializer
                = new XMLSerializer(new FileWriter(pageContext.getServletContext().getRealPath("/student2.xml")), format);
        serializer.serialize(doc);

    %>
  </body>
</html>