Java Dom4j使用

背景:需要调用c#接口获取数据,传参格式为xml,返回值也为xml,因此需要解析xml获取数据。

dom4j介绍:

dom4j是dom4j.orj出品的一个开源XML解析包。它主要应用于Java平台,并采用了Java集合框架并完全支持DOM、SAX和JAXP。

使用思路:创建document 文档对象,然后根据xml的根节点依次拼接elment属性,

代码如下

org.dom4j.Document document=DocumentHelper.createDocument(); 
			document.setXMLEncoding("utf-8");
			Element soapEnvelop=document.addElement("soap:Envelope");
		    soapEnvelop.addAttribute("xmlns:xsi", "http://xxxxxxx")
		    .addNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");
		    soapEnvelop.addAttribute("xmlns:xsd", "http://xxxxxxx")
		    .addNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
		    soapEnvelop.addAttribute("xmlns:soap", "http://xxxxxxxx")
		    .addNamespace("soap", "http://xxxxxx");
		    Element soapheader=soapEnvelop.addElement("soap:Header");
		    Element mysoap=soapheader.addElement("MySoapHeader","http://txxxxxx.org/");
		    Element errinfo=mysoap.addElement("errinfo");
		    errinfo.setText(errinfo1);
		    Element userid=mysoap.addElement("UserID");
		    userid.setText(user_id);
		    Element password1=mysoap.addElement("Password");
		    password1.setText(password);
		    Element soapbody=soapEnvelop.addElement("soap:Body");
		    Element getbsh=soapbody.addElement("GetBsh","http://xxxxxx.org/");
		    Element sfaren1=getbsh.addElement("sFaren");
		    sfaren1.setText(sfaren);
		    Element sbsh01Element=getbsh.addElement("123");
		    sbsh01Element.setText(sbsh01);
		    Element sbsh02Element=getbsh.addElement("1233");
		    sbsh02Element.setText(sbsi02);
		    Element sbsi12Element=getbsh.addElement("12333");
		    sbsi12Element.setText(sbsi12);
		    Element sbsi13Element=getbsh.addElement("12333");
		    sbsi13Element.setText(sbsi13);
		    Element sbdatElement=getbsh.addElement("3221");
		    sbdatElement.setText(sbdate);
		    Element sedateElement=getbsh.addElement("231");
		    sedateElement.setText(sedate);
		    System.out.println(document.asXML());
		    String soapXML=document.asXML();

以上步骤仅仅只是完成了第一步设置参数,只是把参数设置成c#可以识别的xml格式

下一步调用接口将我们定义完成的document对象传入url中

URL url = new URL("https://xxxxxx/zkwebservice.asmx");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			// 3:设置连接参数
			// 3.1设置发送方式:POST必须大写
			connection.setRequestMethod("POST");
			// 3.2设置数据格式:Content-type
			connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
			// 3.3设置输入输出,新创建的connection默认是没有读写权限的,
			connection.setDoInput(true);
			connection.setDoOutput(true);
			java.io.OutputStream os = connection.getOutputStream();
			os.write(soapXML.getBytes());
			logger.info("byte參數1:" + soapXML);
			int responseCode = connection.getResponseCode();
			logger.info("返回Code1:" + responseCode);
			StringBuilder sb = new StringBuilder();
			String resultstr = "";
			if (200 == responseCode) {// 表示服务端响应成功
				logger.info("xml响应成功1");
				InputStream is = connection.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				String temp = null;

				while (null != (temp = br.readLine())) {
					sb.append(temp);
				}
				logger.info("xml响应成功xxx000");
				resultstr = sb.toString();
				logger.info("xml响应成功xxx111000");
				is.close();
				isr.close();
				br.close();
			}
			os.close();//关闭流

将读取数据存入resultstr中,下一步就是读取,将数据处理成我们需要的格式

if (resultstr != null) {
				logger.info("xml响应成功000");
				resultstr = resultstr.substring(resultstr.indexOf("<NewDataSet"),
						resultstr.lastIndexOf("</NewDataSet>") + 13);
				resultstr = resultstr.replace(" xmlns=\"\"", "");
				resultstr = resultstr.replace("diffgr:", "");
				resultstr = resultstr.replace("\" msdata:rowOrder=\"", "");
				org.json.JSONObject json = XML.toJSONObject(resultstr);

				logger.info("xml响应成功111222");
				// 输出json内容
				String result = json.toString();
				result = result.split("\\[|\\]")[1];
				result = "[" + result + "]";
//            result=new String(result.getBytes(),"UTF-8");
				logger.info("xml响应成功222");
				list1.clear();
				list1 = JSONArray.parseArray(result, CMdata.class);
               // System.out.println(list1);
				logger.info("xml响应成功333");
			}
		}catch (RuntimeException runtime) {
			runtime.printStackTrace();// 打印异常信息 
		}
		catch (Exception e) {
		}
	  	logger.info(">>>>>>>>>>>>>>>>>>>>抓取部门资料-END>>>>>>>>>>>>>>>>>>>");

这里的list需要自己去定义类型。

老弟不太行,如果有瑕疵的地方,还望各位大佬指点一二!老弟不胜感激!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
dom4j是一个JavaXML API,用于读写XML文件。它是一个性能优异、功能强大且易于使用的开源库。dom4j没有提供直接的压缩功能,因为它的主要目的是解析和操作XML文件。如果你需要压缩XML文件,你可以使用其他的压缩库,如Java的ZipOutputStream类。下面是一个使用dom4j解析XML文件并将其压缩的示例代码: ```java import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Dom4jZipExample { public static void main(String[] args) { // 读取XML文件 Document document = readXmlFile("input.xml"); // 压缩XML文件 zipXmlFile(document, "output.zip"); } private static Document readXmlFile(String filePath) { Document document = null; try { SAXReader reader = new SAXReader(); document = reader.read(filePath); } catch (DocumentException e) { e.printStackTrace(); } return document; } private static void zipXmlFile(Document document, String zipFilePath) { try { ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath)); ZipEntry zipEntry = new ZipEntry("output.xml"); zipOutputStream.putNextEntry(zipEntry); document.write(zipOutputStream); zipOutputStream.closeEntry(); zipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例代码使用dom4j解析XML文件,并将解析后的内容写入到一个压缩文件中。你可以将需要压缩的XML文件命名为"input.xml",并将压缩后的文件命名为"output.zip"。请确保你已经将dom4j库添加到你的项目中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值