gistfile1.txt //(1) 取得DocumentBuilderFactory类的对象,用于取得DocumentBuilder类的对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ; DocumentBuilder build=null; try{ // (2)取得DocumentBuilder类的对
//(1) 取得DocumentBuilderFactory类的对象,用于取得DocumentBuilder类的对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
DocumentBuilder build=null;
try{
// (2)取得DocumentBuilder类的对象
build= factory.newDocumentBuilder();
}
catch(ParserConfigurationException e){
e.printStackTrace();
}
response.setContentType("application/xml") ;//设置回应的类型为xml
//(3)定义Document接口对象,通过DocumentBuilder类进行DOM树的转换操作
Document doc =null;
doc=build.newDocument() ; // 创建一个新的XML文档
//(4)建立各个操作节点
Element allGoods= doc.createElement("allGoods") ;
doc.appendChild(allGoods) ;//doc为根节点,allGoods为其子节点
Element msg= doc.createElement("msg") ;
Element tCount= doc.createElement("tCount") ;
tCount.appendChild(doc.createTextNode(totalCount+"")) ;
msg.appendChild(tCount);
Element tPage= doc.createElement("tPage") ;
tPage.appendChild(doc.createTextNode(totalPage+"")) ;
msg.appendChild(tPage);
Element nPage= doc.createElement("nPage") ;
nPage.appendChild(doc.createTextNode(page+"")) ;
msg.appendChild(nPage);
allGoods.appendChild(msg);
List
list=null;
try{
list=GoodsDAOProxy.getInstance().selectGoodsByName((page-1)*pageCount,pageCount,key);
}catch(Exception e){
e.printStackTrace();
}
for(Goods g:list){//高级循环迭代输出List集合中各个元素
Element goods= doc.createElement("goods") ;//建立节点
Element id=doc.createElement("id");
Element name= doc.createElement("name") ;
Element description=doc.createElement("description");
Element price=doc.createElement("price");
Element src=doc.createElement("src");
//(5)设置节点内容
id.appendChild(doc.createTextNode(String.valueOf(g.getId())));
name.appendChild(doc.createTextNode(g.getName())) ;
description.appendChild(doc.createTextNode(g.getDescription())) ;
price.appendChild(doc.createTextNode(String.valueOf(g.getPrice())));
src.appendChild(doc.createTextNode(g.getSrc())) ;
//(6) 该设置各个节点的关系
goods.appendChild(id) ;//id为goods的节点
goods.appendChild(name) ;//name为goods的节点
goods.appendChild(description) ;//description为goods的节点
goods.appendChild(price) ;//price为goods的节点
goods.appendChild(src) ;//src为goods的节点
allGoods.appendChild(goods);//goods是allGoods的子节点
}
//(7)输出文档到文件中,创建XML转换器
TransformerFactory tf = TransformerFactory.newInstance() ;
Transformer t =null;
try{
t=tf.newTransformer() ;
}
catch(TransformerConfigurationException e1){
e1.printStackTrace();
}
OutputStream out=response.getOutputStream();//获取应答流
t.setOutputProperty(OutputKeys.INDENT, "yes");// 设置处理中文的编码
DOMSource source = new DOMSource(doc) ; // 准备输出文档,创建数据源
StreamResult result = new StreamResult(out) ;
try{
t.transform(source,result) ;
//System.out.println("生成XML成功");
}
catch(TransformerException e){
e.printStackTrace();
}
