用做示例的XML文件如下:exampleA.xml
<?xml version="1.0" encoding="GB2312"?>
<bookList>
<book hot1="true">
<author>王五</author>
<publishDate>2002-6-6</publishDate>
<price amount="15.00" currency="USD">50.0</price>
<price amount="7.75" currency="GBP" />
<price amount="30000.00" currency="MXP" />
<add sku="123456">add</add>
<attribute sku="123456" sf234="123456" />
<add sku="123456">add</add>
<attribute sku="123456" sf234="123456" />
</book>
<book>
<name>XML在Java中的应用</name>
<author>李四</author>
<publishDate>2002-9-16</publishDate>
<price amount="15.00" currency="USD" />
<price amount="7.75" currency="GBP" />
<price amount="30000.00" currency="MXP" />
</book>
</bookList>
<?xml-stylesheet href="bookList.html.xsl" type="text/xsl"?>
接下来就是在jsp中来调用这两个javabean实现对XML的操作,jsp文件的代码如下:
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="org.jdom.*" %>
<%@ page import="org.jdom.output.*" %>
<%@ page import="org.jdom.input.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="XML.*" %>
<%
//xml文件的路径(绝对路径)
String fileName="exampleA.xml";
String aa=getServletContext().getRealPath("/")+"jdom\\";
String trace=aa+fileName;
//初始化读写的bean
XML.readXML readXmlBean = new XML.readXML();
XML.writeXML writeXmlBean = new XML.writeXML();
//从xml文件中得到相关数据
Document doc;
readXmlBean.readXML(trace);
doc=readXmlBean.getXmlDoc();
//加入一条处理指令
ProcessingInstruction pi = new ProcessingInstruction
("xml-stylesheet","href=\"bookList.html.xsl\" type=\"text/xsl\"");
doc.addContent(pi);
//得到根元素
Element root = doc.getRootElement();
//得到根元素所有子元素的集合
java.util.List books = root.getChildren();
//得到第一个book元素
Element book = (Element)books.get(0);
//为第一本书添加一条属性
Attribute a = new Attribute("hot1","true");
book.setAttribute(a);
//得到指定的字元素
Element author = book.getChild("author");
//将作者改为王五
author.setText("王五");
//得到指定的字元素
Element price = book.getChild("price");
//修改价格
price.setText(Float.toString(50.0f));
//叠代显示所有元素
Iterator it = books.iterator();
共2页 第1页 第2页






