package com.howbuy.fds.webtx.manageself;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
/**
* @author tony
* @create 2011-11-24
*/
public class BankValidateXmlUtil {
@SuppressWarnings("unchecked")
private static Document buildXMLDoc(Map<String, String> paramMap) throws IOException,
JDOMException {
Document doc = new Document();
//创建根节点
Element root = new Element("root");
// 创建节点url,并把url接点添加到根节点下;
root.addContent(new Element("url").setText(getStrValue((String) paramMap.get("url"))));
//创建nodes节点
Element nodesElement = new Element("nodes");
//创建node节点
Iterator it = (Iterator) paramMap.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
if ("url".equals(key)){
continue;
}
Element nodeElement = new Element("node");
nodeElement.addContent(new Element("name").setText(key)); //向node节点中添加内容
nodeElement.addContent(new Element("value").setText(getStrValue((String) paramMap.get(key))));
//将node节点放到nodes节点下
nodesElement.addContent(nodeElement);
}
//将nodes节点放到root节点下
root.addContent(nodesElement);
doc.setRootElement(root);
return doc;
}
/**
* 根据Document输出xml内容
* @param paramMap
* @return
* @throws IOException
* @throws JDOMException
*/
public static String getXmlRsltStr(Map<String, String> paramMap) throws IOException, JDOMException {
Document doc = buildXMLDoc(paramMap);
//将构造的doc输出
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.outputString(doc);
ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
XMLOutputter docWriter = new XMLOutputter();
try {
docWriter.output(doc, byteRep);
return byteRep.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String getStrValue(String str){
if(StringUtils.isEmpty(str))
return "";
return str;
}
/**
* 主方法用于测试
* @param args
*/
public static void main(String[] args) {
try {
Map map = new HashMap<String, String>();
map.put("url", "www.howbuy.com");
map.put("name", "tony");
map.put("age", "21");
String xmlStr = getXmlRsltStr(map);
System.out.println(xmlStr);
} catch (Exception e) {
e.printStackTrace();
}
}
}