dom4j生成XML报文以及CDATA值的设置

接口通讯报文经常遇到需要使用XML报文的情况,这几天刚好与另一个系统做接口开发,对方要求的XML报文格式如下:




   
   
      
         
          
 	
 		2014
 		 		2
 		0001
 		100000
 		CORPMIS
 		TMIS
 		2014-02-27 11:44:33
 		330000000101
 		zjbank1
 		1
 		SafeEnterpriseInfoService.doQueryCorpInfo
 		00012014022700000000
 	
	 
 		
			667869716			
			3多福多寿


       		
	 
 	]]>
      
   



分别采用  org.dom4j.Document 和 org.w3c.dom.Document都生成了上述报文,使用方式上基本相同,感觉DOM4J较为方便,做个记录,其中CDATA中的XML报文可编写另外的方法来组建,代码如下:


public void testOfWriter1(){
		String xml = " "+
			 	""+
			 		"2014"+
			 		 		"2"+
			 		"0001"+
			 		"100000"+
			 		"CORPMIS"+
			 		"TMIS"+
			 		"2014-02-27 11:44:33"+
			 		"330000000101"+
			 		"zjbank1"+
			 		"1"+
			 		"SafeEnterpriseInfoService.doQueryCorpInfo"+
			 		"00012014022700000000"+
			 	""+
				 ""+
			 		""+
						"667869716			"+
						"3多福多寿"+
			       		""+
				 ""+
			 	"";
		
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("soapenv:Envelope");
		root.addNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/").addNamespace("ban", "http://bankin.ws.soa.res.com");
		Element xmlHeader = root.addElement("soapenv:Header");
		Element xmlBody = root.addElement("soapenv:Body");
		Element xmlban = xmlBody.addElement("ban:messageIn");
		xmlban.addElement("ban:request");
		xmlban.addCDATA(xml);
		System.out.println(xml);
		try {
			String fileName = "D:\\Envelope.xml";
			  OutputFormat format = OutputFormat.createPrettyPrint();
			  format.setNewLineAfterDeclaration(false);
			  //format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new FileWriter(fileName),format);
			writer.write(doc);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}



你可能感兴趣的:(JAVA)