红色字体为主要代码
jsp页面中
<script language="javascript">
function updateDB(operate){
var objDom=new ActiveXObject("msxml.DomDocument");
var objRoot=objDom.createElement("All");
objDom.appendChild(objRoot);
var k=document.getElementsByName("check"); //选择框
for(var i=0;i<k.length;i++){
if(k[i].checked){ //将选择的数据组合成xml格式的数据
var currentRow=k[i].parentNode.parentNode;
var obj=objDom.createElement("Good");
objRoot.appendChild(obj);
var objNode=objDom.createElement("xl_id");
objNode.text=k[i].value;
obj.appendChild(objNode);
objNode=objDom.createElement("xqnum");
objNode.text=currentRow.cells[5].childNodes[0].value;
obj.appendChild(objNode);
objNode=objDom.createElement("desc");
objNode.text=currentRow.cells[7].childNodes[0].value;
obj.appendChild(objNode);
}
}
ajaxSendPost("qgApplyAction.do?method="+operate.name,objDom,null);//自己封装的ajax请求 第一个参数为url,第二个为传送参数,第三个是回调函数
}
</script>
后台action.java代码接收xml文件 代码如下
引入的包如下
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
action中的方法
public ActionForward updateApplyDetail(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
List<QGGoodBean> goods=new ArrayList<QGGoodBean>();
String xml =readXMLFromResQuestBody(request);
Document xmlDoc=null;
try {
//用字符串生成内存流,再用内存流生成Document对象。Document的parse方法需要流做为参数
try {
xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes("utf-8")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
//得到所有type元素
NodeList selectedPetTypes = xmlDoc.getElementsByTagName("Good");
for(int i=0;i<selectedPetTypes.getLength();i++){
//selectedPetTypes.item(i)得到Node对象
//selectedPetTypes.item(i).getChildNodes()得到Good的子节点的值
QGGoodBean qgGood=new QGGoodBean();
qgGood.setX_id(selectedPetTypes.item(i).getChildNodes().item(0).getTextContent());
qgGood.setAmount(selectedPetTypes.item(i).getChildNodes().item(1).getTextContent());
qgGood.setRequireDesc(selectedPetTypes.item(i).getChildNodes().item(2).getTextContent());
goods.add(qgGood);
}
response.setContentType("text/xml");
PrintWriter out;
try {
out = response.getWriter();
out.print("aa");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private String readXMLFromResQuestBody(HttpServletRequest request){
StringBuffer xml = new StringBuffer();
String line = null;
try{
BufferedReader reader = request.getReader();
while((line=reader.readLine())!=null){
xml.append(line);
}
}catch(Exception e){
System.out.println("Error reading XML:"+e.toString());
}
return xml.toString();
}