xml报文解析和组装
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(); }
}
}
}
}