这段时间写了一个关于xml报文的工具类,做一下具体的讲解:
xml文本
1711030000054 MNLN CITIC dlm3 GMT 2017-11-03T08:02:54 MNLN CITIC GFWD1700000943 2017-11-03T08:02:54 SHZH00 WHWH SHZH00 201711030000172 PANORAMA INTERFACE EraYTInterface EraYTInterface TXAU AA1 DD AccType ContractCode AUY-CNY/FX UserTradeDate 2017-11-03T08:02:54 TradeOwner AUY CNY 273.69 1 2018-02-07 -90.0 AUY 2 2018-02-07 24632.1 CNY PseudoProduct PseudoProductType
xml转map方法:
/** * xml转map 不带属性 * @param xmlStr * @param needRootKey 是否需要在返回的map里加根节点键 * @return * @throws DocumentException */ public static Map xml2map(String xmlStr, boolean needRootKey) throws DocumentException { SAXReader reader = new SAXReader(); Document doc = reader.read(xmlStr); Element root = doc.getRootElement(); Mapmap = (Map ) xml2map(root); if(root.elements().size()==0 && root.attributes().size()==0){ return map; } if(needRootKey){ //在返回的map里加根节点键(如果需要) Map rootMap = new HashMap (); rootMap.put(root.getName(), map); return rootMap; } return map; } /** * xml转map 带属性 * @param xmlStr * @param needRootKey 是否需要在返回的map里加根节点键 * @return * @throws DocumentException */ public static Map xml2mapWithAttr(String xmlStr, boolean needRootKey) throws DocumentException { SAXReader reader = new SAXReader(); Document doc = reader.read(xmlStr); Element root = doc.getRootElement(); Map map = (Map ) xml2mapWithAttr(root); if(root.elements().size()==0 && root.attributes().size()==0){ return map; //根节点只有一个文本内容 } if(needRootKey){ //在返回的map里加根节点键(如果需要) Map rootMap = new HashMap (); rootMap.put(root.getName(), map); return rootMap; } return map; } /** * xml转map 不带属性 * @param e * @return */ @SuppressWarnings("unchecked") private static Map xml2map(Element e) { Map map = new LinkedHashMap(); List list = e.elements(); if (list.size() > 0) { for (int i = 0; i < list.size(); i++) { Element iter = (Element) list.get(i); List mapList = new ArrayList(); if (iter.elements().size() > 0) { Map m = xml2map(iter); if (map.get(iter.getName()) != null) { Object obj = map.get(iter.getName()); if (!(obj instanceof List)) { mapList = new ArrayList(); mapList.add(obj); mapList.add(m); } if (obj instanceof List) { mapList = (List) obj; mapList.add(m); } map.put(iter.getName(), mapList); } else map.put(iter.getName(), m); } else { if (map.get(iter.getName()) != null) { Object obj = map.get(iter.getName()); if (!(obj instanceof List)) { mapList = new ArrayList(); mapList.add(obj); mapList.add(iter.getText()); } if (obj instanceof List) { mapList = (List) obj; mapList.add(iter.getText()); } map.put(iter.getName(), mapList); } else map.put(iter.getName(), iter.getText()); } } } else map.put(e.getName(), e.getText()); return map; } /** * xml转map 带属性 * @param e * @return */ @SuppressWarnings("unchecked") private static Map xml2mapWithAttr(Element element) { Map map = new LinkedHashMap (); List list = element.elements(); List listAttr0 = element.attributes(); // 当前节点的所有属性的list for (Attribute attr : listAttr0) { map.put("@" + attr.getName(), attr.getValue()); } if (list.size() > 0) { for (int i = 0; i < list.size(); i++) { Element iter = list.get(i); List mapList = new ArrayList(); if (iter.elements().size() > 0) { Map m = xml2mapWithAttr(iter); if (map.get(iter.getName()) != null) { Object obj = map.get(iter.getName()); if (!(obj instanceof List)) { mapList = new ArrayList(); mapList.add(obj); mapList.add(m); } if (obj instanceof List) { mapList = (List) obj; mapList.add(m); } map.put(iter.getName(), mapList); } else map.put(iter.getName(), m); } else { List listAttr = iter.attributes(); // 当前节点的所有属性的list Map attrMap = null; boolean hasAttributes = false; if (listAttr.size() > 0) { hasAttributes = true; attrMap = new LinkedHashMap (); for (Attribute attr : listAttr) { attrMap.put("@" + attr.getName(), attr.getValue()); } } if (map.get(iter.getName()) != null) { Object obj = map.get(iter.getName()); if (!(obj instanceof List)) { mapList = new ArrayList(); mapList.add(obj); // mapList.add(iter.getText()); if (hasAttributes) { attrMap.put("#text", iter.getText()); mapList.add(attrMap); } else { mapList.add(iter.getText()); } } if (obj instanceof List) { mapList = (List) obj; // mapList.add(iter.getText()); if (hasAttributes) { attrMap.put("#text", iter.getText()); mapList.add(attrMap); } else { mapList.add(iter.getText()); } } map.put(iter.getName(), mapList); } else { // map.put(iter.getName(), iter.getText()); if (hasAttributes) { attrMap.put("#text", iter.getText()); map.put(iter.getName(), attrMap); } else { map.put(iter.getName(), iter.getText()); } } } } } else { // 根节点的 if (listAttr0.size() > 0) { map.put("#text", element.getText()); } else { map.put(element.getName(), element.getText()); } } return map; }
执行方法
public static void main(String[] args) throws DocumentException, IOException { String textFromFile = "PMEXCH.xml"; Mapstring=xml2mapWithAttr(textFromFile,false); }
结果是:
{@version=1.03, NTMHeader={MessageID= MessageID , MessageSource={SystemID= SystemID_1 , Location= Location_1 , UserID= UserID_1 }, Timezone=Timezone, DateFormat={@format=ISO8601, #text=}, GeneratedTime= GeneratedTime , PublishResponse={@value=JustLogs, #text=}, TransactMessage={@value=NoTransact, #text=}}, NTMTrade={TradeHeader={SysTradeID={SystemID= SystemID_2 , Location= Location_2 , TradeID= TradeID }, TradeDate= TradeDate , OriginEntity={Entity={@role=Owner, Organization= Organization_1 , Trader= Trader }}, OtherEntity={Entity={@role=Counterparty, Organization= Organization_2 }}, InterestedParties={Entity=[{@role=Broker, Organization= Organization_3 }, {@role=Custodian, Organization= Organization_4 }]}, TradeDescription= TradeDescription , TradeRole={@value=Actual, #text=}, TradeMessageRole={@value=New, #text=}, Notes= Notes_1 , ProcessHistory={ProcessAction={ProcessName=ProcessName, ProcessedOK={@value=Yes, #text=}, Notes= Notes_2 }}}, TradeTags={TradingArea= TradingArea , AccountingArea= AccountingArea , AccountingGroup= AccountingGroup , TicketID= TicketID , Extensions={Extension=[{ExtName= ExtName_1 , ExtValue={@datatype=String, #text=}}, {ExtName= ExtName_2 , ExtValue={@datatype=String, #text=}}, {ExtName=ExtName_3, ExtValue={@datatype=Datetime, #text=}}, {ExtName=ExtName_4, ExtValue={@datatype=String, #text=}}]}}, FX={FXRate={NumeratorCCY={CCY= CCY_1 }, DenominatorCCY={CCY= CCY_2 }, Rate= Rate }, BuyCFL={Cashflow={@CFLType=Principal, CashflowID= CashflowID_1 , CashflowPayment={PayDate= PayDate_1 , Amount= amount_1 , CCY= CCY_3 }}}, SellCFL={Cashflow={@CFLType=Principal, CashflowID= CashflowID_2 , CashflowPayment={PayDate= PayDate_2 , Amount= amount_2 , CCY= CCY_4 }}}}, Extensions={Extension=[{ExtName= ExtName_5 , ExtValue={@datatype=String, #text=}}, {ExtName= ExtName_6 , ExtValue={@datatype=String, #text=}}]}}}
map转xml的方法
/** * map转xml map中没有根节点的键 * * @param map * @param rootName * 父节点 * @throws DocumentException * @throws IOException */ public static Document mapToxml(Mapmap, String rootName) throws DocumentException, IOException { Document doc = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement(rootName); doc.add(root); mapToxml(map, root); return doc; } /** * map转xml map中含有根节点的键 * * @param map * @throws DocumentException * @throws IOException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Document mapToxml(Map map) throws DocumentException, IOException { Iterator > entries = map.entrySet().iterator(); if (entries.hasNext()) { // 获取第一个键创建根节点 Map.Entry entry = entries.next(); Document doc = DocumentHelper.createDocument(); Element root = DocumentHelper.createElement(entry.getKey()); doc.add(root); mapToxml((Map) entry.getValue(), root); return doc; } return null; } /** * map转xml * * @param map * @param body * xml节点元素 * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Element mapToxml(Map map, Element body) { Iterator > entries = map.entrySet().iterator(); while (entries.hasNext()) { // 遍历entries Map.Entry entry = entries.next(); String key = entry.getKey(); Object value = entry.getValue(); if (key.startsWith("@")) { // 属性 body.addAttribute(key.substring(1, key.length()), value.toString()); } else if (key.equals("#text")) { // 有属性时的文本 body.setText(value.toString()); } else { if (value instanceof java.util.List) { List list = (List) value; Object obj; for (int i = 0; i < list.size(); i++) { obj = list.get(i); // list里是map或String,不会存在list里直接是list的, if (obj instanceof java.util.Map) { Element subElement = body.addElement(key); mapToxml((Map) list.get(i), subElement); } else { body.addElement(key).setText((String) list.get(i)); } } } else if (value instanceof java.util.Map) { Element subElement = body.addElement(key); mapToxml((Map) value, subElement); } else { body.addElement(key).setText(value.toString()); } } } return body; }
格式化xml
/** * 格式化输出xml * * @param xmlStr * xml文件 * @return * @throws DocumentException * @throws IOException */ public static String formatXml(String xmlStr) throws DocumentException, IOException { Document document = DocumentHelper.parseText(xmlStr); return formatXml(document); } /** * 格式化输出xml * * @param document * @return * @throws DocumentException * @throws IOException */ public static String formatXml(Document document) throws DocumentException, IOException { // 格式化输出格式 OutputFormat format = OutputFormat.createPrettyPrint(); StringWriter writer = new StringWriter(); // 格式化输出流 XMLWriter xmlWriter = new XMLWriter(writer, format); // 将document写入到输出流 xmlWriter.write(document); xmlWriter.close(); return writer.toString(); }执行结果
1711030000054 MNLN CITIC dlm3 GMT 2017-11-03T08:02:54 MNLN CITIC GFWD1700000943 2017-11-03T08:02:54 SHZH00 WHWH SHZH00 201711030000172 PANORAMA INTERFACE EraYTInterface EraYTInterface TXAU AA1 DD AccType ContractCode AUY-CNY/FX UserTradeDate 2017-11-03T08:02:54 TradeOwner AUY CNY 273.69 1 2018-02-07 -90.0 AUY 2 2018-02-07 24632.1 CNY PseudoProduct PseudoProductType