输出xml

输出xml

在struts2.Xml中写:
<? xml version = " 1.0 "  encoding = " UTF-8 " ?>
 
<! DOCTYPE struts PUBLIC
    
" -//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN "
    
" http://struts.apache.org/dtds/struts-2.1.7.dtd " >
    
< struts >
        
< package  name = " myxml "    extends = " struts-default " >
        
<!--  输出xml的方法不写result  -->
            
< action name = " xml "   class = " com.yjw.web.MyxmlAction " ></ action >
        
</ package >
    
</ struts >
在action中写:
package  com.yjw.web;

import  java.io.PrintWriter;

import  javax.servlet.http.HttpServletResponse;

import  org.apache.struts2.ServletActionContext;

import  com.opensymphony.xwork2.Action;

public   class  MyxmlAction  implements   Action {

    
public String execute() throws Exception {
        HttpServletResponse  response 
= ServletActionContext.getResponse();
        response.setContentType(
"text/xml;charset=UTF-8");
        PrintWriter  out 
= response.getWriter();
        out.print(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.print(
"<root>");
        
for(int i=0;i<5;i++){
            out.print(
"<person>");
            out.print(
"<name>person"+i+"</name>");
            out.print(
"</person>");
        }

        out.print(
"</root>");
        
//一定要返回null
        return null;
    }


}

在jsp里写:
< body >
  
< input  type = " button "   value = " xml "   id = " btnxml " />
  
< div  id = " mydiv " ></ div >
  
< script type = " text/javascript "   src = js / jquery - 1.5 . 1 .min.js ></ script >
  
< script  type = " text/javascript " >
              $(document).ready(function()
{
                  $(
"#btnxml").click(function(){
                      $.get(
"xml.action",function(xml){
                          $(xml).find(
"person").each(function(){
                              var name 
= $(this).find("name").text();
                              $(
"#mydiv").html($("#mydiv").html()+name+'<br/>');
                          }
);
                      }
);
                      
                  }
);
              }
);
  
</ script >
  
</ body >

你可能感兴趣的:(输出xml)