package com.xjts.cipher.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONType;
import com.xjts.model.XmlEngine;
public class XmlGen {
/*****************************
* 組裝請求xml串
* list 數據庫中配置的報文頭,報文體
* map 請求參數
*****************************/
public static String assembleRequestXml(List<XmlEngine> list, Map<String, String> map) {
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("message");
Element head = root.addElement("head");
Set<Map.Entry<String, String>> itermap = map.entrySet();
for(Map.Entry<String, String> entry: itermap){
String key = entry.getKey();
String value = entry.getValue();
for(int i = 0; i < list.size(); i++ ){
if(key.equals(list.get(i).getName().substring(10))){
list.get(i).setDefaultvalue(value);
}
}
}
for(int i = 0; i < list.size(); i++){
if("head".equals(list.get(i).getName().substring(0, 4))){
Element field = head.addElement("field");
field.addAttribute("name",
list.get(i).getName().substring(10));
String str = list.get(i).getDefaultvalue();
if (null != str && !"".equals(str)){
field.addAttribute("name",
list.get(i).getName().substring(10))
.setText(str);
}
}
}
Element body = root.addElement("body");
for(int i = 0; i < list.size(); i++){
if("body".equals(list.get(i).getName().substring(0, 4))){
Element field = body.addElement("field");
field.addAttribute("name",
list.get(i).getName().substring(10));
String str = list.get(i).getDefaultvalue();
if (null != str && !"".equals(str)){
field.addAttribute("name",
list.get(i).getName().substring(10))
.setText(str);
}
}
}
OutputFormat format = OutputFormat.createPrettyPrint();
//.createCompactFormat(); //createPrettyPrint() 輸出格式化
format.setEncoding("gb2312");
StringWriter writer = new StringWriter();
XMLWriter output = new XMLWriter(writer, format);
try {
output.write(doc);
writer.close();
output.close();
// System.out.println(writer.toString());
} catch (IOException e) {
e.printStackTrace();
return null;
}
String content=writer.toString();
StringBuilder sb = new StringBuilder();
sb.append(content);
//加入 standalone="yes"
// sb.insert(37, " standalone=\"yes\"");
return sb.toString();
}
/***********************************************
* 組裝響應xml串
* list xml中head和body內的標簽
* map xml中head和body內的標簽的key-value
* listDetail 應答報文的明細數據,記錄
***********************************************/
public static String assembleResponseXml(List<XmlEngine> list, Map<String, String> map
, List<Map<String, String>> listDetail){
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("message");
Element head = root.addElement("head");
Set<Map.Entry<String, String>> itermap = map.entrySet();
for(Map.Entry<String, String> entry: itermap){
String key = entry.getKey();
String value = entry.getValue();
for(int i = 0; i < list.size(); i++ ){
if(key.equals(list.get(i).getName().substring(10))){
list.get(i).setDefaultvalue(value);
}
}
}
for(int i = 0; i < list.size(); i++){
if("head".equals(list.get(i).getName().substring(0, 4))){
Element field = head.addElement("field");
field.addAttribute("pin",
"false");
field.addAttribute("name",
list.get(i).getName().substring(10));
String str = list.get(i).getDefaultvalue();
if (null != str && !"".equals(str)){
field.addAttribute("name",
list.get(i).getName().substring(10))
.addCDATA(str);
}else{
field.addAttribute("name",
list.get(i).getName().substring(10))
.addCDATA("");
}
}
}
Element body = root.addElement("body");
for(int i = 0; i < list.size(); i++){
if("body".equals(list.get(i).getName().substring(0, 4))){
Element field = body.addElement("field");
field.addAttribute("pin",
"false");
field.addAttribute("name",
list.get(i).getName().substring(10));
String str = list.get(i).getDefaultvalue();
if (null != str && !"".equals(str)){
field.addAttribute("name",
list.get(i).getName().substring(10))
.addCDATA(str);
}
}
}
if(listDetail != null){
if(listDetail.size() != 0){
Element field1 = body.addElement("field-list");
field1.addAttribute("name",
"ARRAY_" + list.get(0).getName().substring(4, 10));
for(int i = 0; i < listDetail.size(); i++){
Element field2 = field1.addElement("field-list");
field2.addAttribute("name",
"" + i);
Set<Map.Entry<String, String>> itermap1 = listDetail.get(i).entrySet();
for(Map.Entry<String, String> entry: itermap1){
String key = entry.getKey();
String value = entry.getValue();
Element field3 = field2.addElement("field");
field3.addAttribute("pin",
"false");
field3.addAttribute("name",
key).addCDATA(value);;
}
}
}
}
OutputFormat format = OutputFormat.createPrettyPrint();
//createCompactFormat(); //createPrettyPrint() 格式化
format.setEncoding("gb2312");
StringWriter writer = new StringWriter();
XMLWriter output = new XMLWriter(writer, format);
try {
output.write(doc);
writer.close();
output.close();
// System.out.println(writer.toString());
} catch (IOException e) {
e.printStackTrace();
return null;
}
return writer.toString();
}
/********************************************
* 針對List<Map<String, String>>類型的對象
* 轉為Json串,此方法和 parseXmlStr(String xml)
* 有關聯
********************************************/
public static String listMap2Json(List<Map<String, String>> listMap){
if(listMap == null) return "null";
String jsonXmlStr = JSON.toJSONString(listMap);
String[] splitStr = jsonXmlStr.split("\\{\"\\d{1,2}\":\"\"\\}");
String retStr = splitStr[0];
for(int i = 1; i < splitStr.length; i++){
retStr += splitStr[i].replaceAll("\\},\\{", ",").substring(1);
}
return retStr;
}
/*****************************
* 解析xml串,返回Map對象
*****************************/
public static List<Map<String, String>> parseXmlStr(String xml) throws Exception {
//final SAXReader sax = new SAXReader();// 創建一個SAXReader對象
//final File xmlFile = new File("E:\\req_message.xml");// 根據指定的路徑創建file對象
//final Document document = sax.read(xmlFile);// 獲取document對象,如果文檔無節點,則會拋出Exception提前結束
Document document = DocumentHelper.parseText(xml);
final Element root = document.getRootElement();// 獲取根節點
List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
getNodes(root, listMap);// 從根節點開始遍歷所有節點
return listMap;
}
/**
* 從指定節點Element node開始,遞歸遍歷其所有子節點
*/
public static void getNodes(final Element node, List<Map<String,String>> listMap) {
//System.out.println("-------開始新節點-------------");
String str = node.getTextTrim();
// 當前節點的名稱、文本內容和屬性
//System.out.println("當前節點名稱:" + node.getName());// 當前節點名稱
//System.out.println("當前節點的內容:" + node.getTextTrim());// 當前節點內容
final List<Attribute> listAttr = node.attributes();// 當前節點的所有屬性
for (final Attribute attr : listAttr) {// 遍歷當前節點的所有屬性
final String name = attr.getName();// 屬性名稱
final String value = attr.getValue();// 屬性的值
//System.out.println("屬性名稱:" + name + "---->屬性值:" + value);
if ("name".equals(name)) {
Map map = new LinkedHashMap();
map.put(value, str);
listMap.add( map);
}
}
// 遞歸遍歷當前節點所有的子節點
final List<Element> listElement = node.elements();// 所有一級子節點的list
for (final Element e : listElement) {// 遍歷所有一級子節點
getNodes(e, listMap);// 遞歸
}
}
/**
* 從指定節點Element node開始,遞歸遍歷其所有子節點
*/
public static void getNodes(final Element node, Map map) {
String str = node.getTextTrim();
final List<Attribute> listAttr = node.attributes();
for (final Attribute attr : listAttr) {
final String name = attr.getName();
final String value = attr.getValue();
if (null != name && !"".equals(str)) {
if ("name".equals(name)) {
map.put(value, str);
}
}
}
final List<Element> listElement = node.elements();
for (final Element e : listElement) {
getNodes(e, map);//遞歸調用
}
}
public void saveDocument(Document document, File outputXml){
try {
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter output = new XMLWriter(new FileWriter(outputXml),
format);
output.write(document);
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String [] argv){
XmlGen dom4j = new XmlGen();
Document document = null;
dom4j.saveDocument(document, new File("output.xml"));
//System.out.println(assembleResponseXml(null, null));
}
public class StandaloneWriter extends XMLWriter {
protected void writeDeclaration() throws IOException {
OutputFormat format = getOutputFormat();
String encoding = format.getEncoding();
if (!format.isSuppressDeclaration()) {
writer.write("<?xml version=\"1.0\"");
if (!format.isOmitEncoding()) {
if (encoding.equals("UTF8"))
writer.write(" encoding=\"UTF-8\"");
else
writer.write(" encoding=\"" + encoding + "\"");
}
writer.write(" standalone=\"true\"");
writer.write("?>");
if (format.isNewLineAfterDeclaration()) { println(); }
}
}
}
}