这段时间写了一个关于xml报文的工具类,做一下具体的讲解:

xml文本

<NTMMessage version="1.03">
<NTMHeader>
<MessageID>1711030000054</MessageID>
<MessageSource>
<SystemID>MNLN</SystemID>
<Location>CITIC</Location>
<UserID>dlm3</UserID>
</MessageSource>
<Timezone>GMT</Timezone>
<DateFormat format="ISO8601"/>
<GeneratedTime>2017-11-03T08:02:54</GeneratedTime>
<PublishResponse value="JustLogs"></PublishResponse>
<TransactMessage value="NoTransact"></TransactMessage>
</NTMHeader>
<NTMTrade>
<TradeHeader>
<SysTradeID>
<SystemID>MNLN</SystemID>
<Location>CITIC</Location>
<TradeID>GFWD1700000943</TradeID>
</SysTradeID>
<TradeDate>2017-11-03T08:02:54</TradeDate>
<OriginEntity>
<Entity role="Owner">
<Organization>SHZH00</Organization>
<Trader>WHWH</Trader>
</Entity>
</OriginEntity>
<OtherEntity>
<Entity role="Counterparty">
<Organization>SHZH00</Organization>
</Entity>
</OtherEntity>
<InterestedParties>
<Entity role="Broker">
<Organization></Organization>
</Entity>
<Entity role="Custodian">
<Organization></Organization>
</Entity>
</InterestedParties>
<TradeDescription>201711030000172</TradeDescription>
<TradeRole value="Actual"/>
<TradeMessageRole value="New"/>
<Notes>PANORAMA INTERFACE</Notes>
<ProcessHistory>
<ProcessAction>
<ProcessName>EraYTInterface</ProcessName>
<ProcessedOK value="Yes"/>
<Notes>EraYTInterface</Notes>
</ProcessAction>
</ProcessHistory>
</TradeHeader>
<TradeTags>
<TradingArea>TXAU</TradingArea>
<AccountingArea>AA1</AccountingArea>
<AccountingGroup>DD</AccountingGroup>
<TicketID></TicketID>
<Extensions>
<Extension>
<ExtName>AccType</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
<Extension>
<ExtName>ContractCode</ExtName>
<ExtValue datatype="String">AUY-CNY/FX</ExtValue>
</Extension>
<Extension>
<ExtName>UserTradeDate</ExtName>
<ExtValue datatype="Datetime">2017-11-03T08:02:54</ExtValue>
</Extension>
<Extension>
<ExtName>TradeOwner</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
</Extensions>
</TradeTags>
<FX>
<FXRate>
<NumeratorCCY>
<CCY>AUY</CCY>
</NumeratorCCY>
<DenominatorCCY>
<CCY>CNY</CCY>
</DenominatorCCY>
<Rate>273.69</Rate>
</FXRate>
<BuyCFL>
<Cashflow CFLType="Principal">
<CashflowID>1</CashflowID>
<CashflowPayment>
<PayDate>2018-02-07</PayDate>
<Amount>-90.0</Amount>
<CCY>AUY</CCY>
</CashflowPayment>
</Cashflow>
</BuyCFL>
<SellCFL>
<Cashflow CFLType="Principal">
<CashflowID>2</CashflowID>
<CashflowPayment>
<PayDate>2018-02-07</PayDate>
<Amount>24632.1</Amount>
<CCY>CNY</CCY>
</CashflowPayment>
</Cashflow>
</SellCFL>
</FX>
<Extensions>
<Extension>
<ExtName>PseudoProduct</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
<Extension>
<ExtName>PseudoProductType</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
</Extensions>
</NTMTrade>
</NTMMessage>

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();
Map<String, Object> map = (Map<String, Object>) xml2map(root);
if(root.elements().size()==0 && root.attributes().size()==0){
return map;
}
if(needRootKey){
//在返回的map里加根节点键(如果需要)
Map<String, Object> rootMap = new HashMap<String, Object>();
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<String, Object> map = (Map<String, Object>) xml2mapWithAttr(root);
if(root.elements().size()==0 && root.attributes().size()==0){
return map; //根节点只有一个文本内容
}
if(needRootKey){
//在返回的map里加根节点键(如果需要)
Map<String, Object> rootMap = new HashMap<String, Object>();
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<String, Object> map = new LinkedHashMap<String, Object>(); List<Element> list = element.elements();
List<Attribute> 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<Attribute> listAttr = iter.attributes(); // 当前节点的所有属性的list
Map<String, Object> attrMap = null;
boolean hasAttributes = false;
if (listAttr.size() > 0) {
hasAttributes = true;
attrMap = new LinkedHashMap<String, Object>();
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";
Map<String, Object> string=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(Map<String, Object> map, 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<String, Object> map)
throws DocumentException, IOException {
Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
if (entries.hasNext()) {
// 获取第一个键创建根节点
Map.Entry<String, Object> 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<String, Object> map, Element body) {
Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
// 遍历entries
Map.Entry<String, Object> 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();
}执行结果
<NTMMessage version="1.03">
<NTMHeader>
<MessageID>1711030000054</MessageID>
<MessageSource>
<SystemID>MNLN</SystemID>
<Location>CITIC</Location>
<UserID>dlm3</UserID>
</MessageSource>
<Timezone>GMT</Timezone>
<DateFormat format="ISO8601"/>
<GeneratedTime>2017-11-03T08:02:54</GeneratedTime>
<PublishResponse value="JustLogs"></PublishResponse>
<TransactMessage value="NoTransact"></TransactMessage>
</NTMHeader>
<NTMTrade>
<TradeHeader>
<SysTradeID>
<SystemID>MNLN</SystemID>
<Location>CITIC</Location>
<TradeID>GFWD1700000943</TradeID>
</SysTradeID>
<TradeDate>2017-11-03T08:02:54</TradeDate>
<OriginEntity>
<Entity role="Owner">
<Organization>SHZH00</Organization>
<Trader>WHWH</Trader>
</Entity>
</OriginEntity>
<OtherEntity>
<Entity role="Counterparty">
<Organization>SHZH00</Organization>
</Entity>
</OtherEntity>
<InterestedParties>
<Entity role="Broker">
<Organization></Organization>
</Entity>
<Entity role="Custodian">
<Organization></Organization>
</Entity>
</InterestedParties>
<TradeDescription>201711030000172</TradeDescription>
<TradeRole value="Actual"/>
<TradeMessageRole value="New"/>
<Notes>PANORAMA INTERFACE</Notes>
<ProcessHistory>
<ProcessAction>
<ProcessName>EraYTInterface</ProcessName>
<ProcessedOK value="Yes"/>
<Notes>EraYTInterface</Notes>
</ProcessAction>
</ProcessHistory>
</TradeHeader>
<TradeTags>
<TradingArea>TXAU</TradingArea>
<AccountingArea>AA1</AccountingArea>
<AccountingGroup>DD</AccountingGroup>
<TicketID></TicketID>
<Extensions>
<Extension>
<ExtName>AccType</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
<Extension>
<ExtName>ContractCode</ExtName>
<ExtValue datatype="String">AUY-CNY/FX</ExtValue>
</Extension>
<Extension>
<ExtName>UserTradeDate</ExtName>
<ExtValue datatype="Datetime">2017-11-03T08:02:54</ExtValue>
</Extension>
<Extension>
<ExtName>TradeOwner</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
</Extensions>
</TradeTags>
<FX>
<FXRate>
<NumeratorCCY>
<CCY>AUY</CCY>
</NumeratorCCY>
<DenominatorCCY>
<CCY>CNY</CCY>
</DenominatorCCY>
<Rate>273.69</Rate>
</FXRate>
<BuyCFL>
<Cashflow CFLType="Principal">
<CashflowID>1</CashflowID>
<CashflowPayment>
<PayDate>2018-02-07</PayDate>
<Amount>-90.0</Amount>
<CCY>AUY</CCY>
</CashflowPayment>
</Cashflow>
</BuyCFL>
<SellCFL>
<Cashflow CFLType="Principal">
<CashflowID>2</CashflowID>
<CashflowPayment>
<PayDate>2018-02-07</PayDate>
<Amount>24632.1</Amount>
<CCY>CNY</CCY>
</CashflowPayment>
</Cashflow>
</SellCFL>
</FX>
<Extensions>
<Extension>
<ExtName>PseudoProduct</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
<Extension>
<ExtName>PseudoProductType</ExtName>
<ExtValue datatype="String"></ExtValue>
</Extension>
</Extensions>
</NTMTrade>
</NTMMessage>

 

解析xml报文,xml与map互转的更多相关文章

  1. xml报文解析和组装

    package com.xjts.cipher.util;import java.io.File;import java.io.FileWriter;import java.io.IOExceptio ...

  2. xml报文的装配解析

    xstream dom 将map自动转化为xml报文 http://blog.csdn.net/lisheng19870305/article/details/45847985 报文的通信

  3. Java开发笔记(一百零九)XML报文的定义和解析

    前面介绍了JSON格式的报文解析,虽然json串短小精悍,也能有效表达层次结构,但是每个元素只能找到对应的元素值,不能体现更丰富的样式特征.比如某个元素除了要传输它的字符串文本,还想传输该文本的类型. ...

  4. java 写webservice接口解析xml报文

    1 <!--解析xml报文--> 2 <dependency> 3 <groupId>dom4j</groupId> 4 <artifactId& ...

  5. PHP通过XML报文格式的POST请求方式,与第三方接口交互(发送xml,获取XML,并解析xml步骤)

    开发者端:发送请求,并接收结果 <?php // 下面的demo,实现的功能如下: // 1-开发者需要判断一个用户是否存在,去请求第三方接口. // 2-与第三方接口的通信,是以xml格式传送 ...

  6. 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)

    1.android下junit测试框架配置 单元测试需要在手机中进行安装测试 (1).在清单文件中manifest节点下配置如下节点 <instrumentation android:name= ...

  7. 在.NET2.0中解析Json和Xml

    在.NET解析json有很多方法,这里介绍最简单也用的最多的一种. 一.添加引用 解析Json,先下载开源控件 Newtonsoft.Json.dll 下载地址:http://files.cnblog ...

  8. Xml格式数据转map工具类

    前言[ 最近在写一个业务,由于调UPS物流的接口返回的是一个xml格式的数据结果,我现在要拿到xml中某个节点的值,而这个xml数据是多节点多层级的,并且这某个节点的值有可能只有一条值,有可能有多条, ...

  9. Xml解析作业与Xml建模andXml建模作业

    作业:config.xml解析 1.获取所有action中的type的值 public static void main(String[] args) throws Exception { Input ...

随机推荐

  1. python第四课——运算符

    一.python中的运算符: 什么是运算符? 就是计算机语言中用来参与运算的符号!! 1.算数运算符: 符号:+ - * / %(取余,取模) //(取整) **(开方) 2.比较运算符: 特点:比较 ...

  2. C++编译器符号表有哪些内容?

    http://blog.csdn.net/wangbingcsu/article/details/48340479 C++编译器符号表有哪些内容? 很早就想写一篇关于符号表的学习小结,可是迟迟不能下笔 ...

  3. Hadoop学习之路(十五)MapReduce的多Job串联和全局计数器

    MapReduce 多 Job 串联 需求 一个稍复杂点的处理逻辑往往需要多个 MapReduce 程序串联处理,多 job 的串联可以借助 MapReduce 框架的 JobControl 实现 实 ...

  4. 【转】打包2个10g文件 测试

    微博上kevin_prajna提了一个问题:“求Linux下一打包工具,需求:能把两个10G的文件打包成一个文件,时间在1分钟之内能接受!”. 暂且作答一下吧.首先问题是求解工具,那么我们忽略IO问题 ...

  5. HDU 1203 01背包变形题,(新思路)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1203 I NEED A OFFER! Time Limit: 2000/1000 MS (Java/ ...

  6. STM32中用 stop 模式 配合低功耗模式下的自动唤醒(AWU) 能否实现FreeRTOS tickless 模式

    已经实现  ,2018年11月17日11:56:42,具体 如下: 第一步 : 修改 void vPortSetupTimerInterrupt( void ) 函数 ,修改原来的 systick 定 ...

  7. Centos7安装elasticsearch、logstash、kibana、elasticsearch head

    环境:Centos7, jdk1.8 安装logstash 1.下载logstash 地址:https://artifacts.elastic.co/downloads/logstash/logsta ...

  8. index range scan,index fast full scan,index skip scan发生的条件

    源链接:https://blog.csdn.net/robinson1988/article/details/4980611 index range scan(索引范围扫描): 1.对于unique ...

  9. js遍历添加栏目类添加css 再点击其它删除css

    //js遍历添加栏目类添加css 再点击其它删除css $(".radio-group .ckselect").each(function(index) { $(this).cli ...

  10. head 标签里有什么?

    head 标签里有什么? 每一个 HTML 文档中,都有一个不可或缺的标签:<head> ,它作为一个容器,主要包含了用于描述 HTML 文档自身信息(元数据)的标签,这些标签一般不会在页 ...