http://yangzi09150915.blog.163.com/blog/static/32953487201072911410398/
package com.aibi.cmdc.webService;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.AttributesImpl;
public class XmlUtil {
/**
* 取得所有prompts 下prompt及其属性 将其转成list<Map<key,value>>
* @param xmlDoc
* @return
*/
@SuppressWarnings("unchecked")
public static List<Map<String, String>> getPrompts(String xmlDoc) {
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
// 创建一个新的字符串
StringReader read = new StringReader(xmlDoc);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
try {
// 通过输入源构造一个Document
Document doc = sb.build(source);
// 取的根元素
Element root = doc.getRootElement();
// 得到根元素所有子元素的集合
List<Element> oneLevelNodes = root.getChildren();
for (int i = 0; i < oneLevelNodes.size(); i++) {
Element oneLevelNode = oneLevelNodes.get(i);
if(oneLevelNode.getName().equals("prompts")){
List<Element> prompts = oneLevelNode.getChildren();
for (int j = 0; j < prompts.size(); j++) {
Map<String, String> promptMap = new HashMap<String, String>();
Element prompt = prompts.get(j);
List<?> attributes =prompt.getAttributes();
for (int k = 0; k < attributes.size(); k++) {
String attribute = attributes.get(k).toString();
System.out.println( attributes.get(k));
String[] keyAndvalue = attribute.split(":")[1].trim().replace("]", "").split("=");
String key = keyAndvalue[0];
String value = keyAndvalue[1].replaceAll("\"", "");
promptMap.put(key, value);
}
list.add(promptMap);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(list);
return list;
}
/**
* list<Map<key,value>> 转换成 prompts xml字符串形式
* @param prompts
* @return
*/
public static String promptsToXmlString(List<Map<String, String>> prompts){
String resultXmlString ="";
try {
// Result resultXml = new StreamResult(new FileOutputStream("d:\\person.xml"));
//用来得到XML字符串形式
// 一个字符流,可以用其回收在字符串缓冲区中的输出来构造字符串
StringWriter writerStr = new StringWriter();
// 构建转换结果树所需的信息。
Result resultStr = new StreamResult(writerStr);
SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
TransformerHandler tfHandler = factory.newTransformerHandler();
Transformer transformer = tfHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //编码格式是UTF-8
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //换行
// tfHandler.setResult(resultXml);
tfHandler.setResult(resultStr);
tfHandler.startDocument();
AttributesImpl attr = new AttributesImpl();
tfHandler.startElement("", "", "prompts", attr); //定义person节点
for (Map<String, String> map : prompts) {
attr.clear();
for(String key : map.keySet()){
attr.addAttribute("", "", key, "", map.get(key));
}
tfHandler.startElement("", "", "prompt", attr); //定义person节点
tfHandler.endElement("", "", "prompt");
}
tfHandler.endElement("", "", "prompts");
tfHandler.endDocument(); //结束xml文档
resultXmlString = writerStr.getBuffer().toString();
} catch (Exception e) {
e.printStackTrace();
}
return resultXmlString;
}
public static void main(String[] args) {
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
for (int i = 0; i < 5; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("dpId", "DP0");
map.put("id", String.valueOf((Math.random()*10)));
map.put("type", "sapVariable");
map.put("optional", "true");
map.put("technicalName", "S_CPDLB");
map.put("name", "产品大类");
list.add(map);
}
String resultXmlString = promptsToXmlString(list);
System.out.println(resultXmlString);
String xmlString = "<returnResult><errCode>S</errCode><errMsg></errMsg><prompts>" +
"<prompt dpId=\"DP0\" id=\"0\" type=\"sapVariable\" optional=\"true\" technicalName=\"S_CPDLB\" name=\"产品大类\" ></prompt>"+
"<prompt dpId=\"DP0\" id=\"1\" type=\"sapVariable\" optional=\"true\" technicalName=\"0S_MATGR\" name=\"Material group\" ></prompt>"+
"<prompt dpId=\"DP0\" id=\"2\" type=\"sapVariable\" optional=\"true\" technicalName=\"0S_MATERIAL\" name=\"Material\" ></prompt>"+
"<prompt dpId=\"DP0\" id=\"3\" type=\"sapVariable\" optional=\"true\" technicalName=\"0S_SALESORG\" name=\"Sales Organization\" ></prompt>"+
"<prompt dpId=\"DP0\" id=\"4\" type=\"sapVariable\" optional=\"true\" technicalName=\"S_ZPLTYP\" name=\"渠道细类\" ></prompt>"+
"<prompt dpId=\"DP0\" id=\"5\" type=\"sapVariable\" optional=\"true\" technicalName=\"0S_CUSTOMER\" name=\"Customer\" ></prompt>"+
"<prompt dpId=\"DP0\" id=\"6\" type=\"sapVariable\" optional=\"true\" technicalName=\"0I_DAYIN\" name=\"Day Interval\" ></prompt>"+
"<prompt dpId=\"DP0\" id=\"7\" type=\"sapVariable\" optional=\"true\" technicalName=\"0I_DAY\" name=\"DATE\" ></prompt>"+
"</prompts></returnResult>";
getPrompts(xmlString);
}
}