Dom4j 生成XML文档与解析XML文档

java开发 专栏收录该内容
12 篇文章 0 订阅
package com.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 
 * @author zhangxj Dom4j 生成XML文档与解析XML文档
 */
public class Dom4jDemo {

	public void readStringXml(String xml) {
		Document doc = null;
		try {

			// 读取并解析XML文档

			// SAXReader就是一个管道,用一个流的方式,把xml文件读出来

			// SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档

			// Document document = reader.read(new File("User.hbm.xml"));

			// 下面的是通过解析xml字符串的

			doc = DocumentHelper.parseText(xml); // 将字符串转为XML

			Element rootElt = doc.getRootElement(); // 获取根节点

			System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称

			Iterator iter = rootElt.elementIterator("head"); // 获取根节点下的子节点head

			// 遍历head节点

			while (iter.hasNext()) {

				Element recordEle = (Element) iter.next();
				String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值

				System.out.println("title:" + title);

				Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script

				// 遍历Header节点下的Response节点

				while (iters.hasNext()) {

					Element itemEle = (Element) iters.next();

					String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值

					String password = itemEle.elementTextTrim("password");

					System.out.println("username:" + username);
					System.out.println("password:" + password);
				}
			}
			Iterator iterss = rootElt.elementIterator("body"); // /获取根节点下的子节点body

			// 遍历body节点

			while (iterss.hasNext()) {

				Element recordEless = (Element) iterss.next();
				String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值

				System.out.println("result:" + result);

				Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form

				// 遍历Header节点下的Response节点

				while (itersElIterator.hasNext()) {

					Element itemEle = (Element) itersElIterator.next();

					String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值

					String subID = itemEle.elementTextTrim("subID");

					System.out.println("banlce:" + banlce);
					System.out.println("subID:" + subID);
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	/**
	 * @description 将xml字符串转换成map
	 * @param xml
	 * @return Map
	 */
	
	public static Map readStringXmlOut(String xml) {
		Map map = new HashMap();
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML

			Element rootElt = doc.getRootElement(); // 获取根节点

			System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称

			Iterator iter = rootElt.elementIterator("head"); // 获取根节点下的子节点head

			// 遍历head节点

			while (iter.hasNext()) {

				Element recordEle = (Element) iter.next();
				String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值

				System.out.println("title:" + title);
				map.put("title", title);

				Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script

				// 遍历Header节点下的Response节点

				while (iters.hasNext()) {

					Element itemEle = (Element) iters.next();

					String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值

					String password = itemEle.elementTextTrim("password");

					System.out.println("username:" + username);
					System.out.println("password:" + password);
					map.put("username", username);
					map.put("password", password);

				}
			}

			Iterator iterss = rootElt.elementIterator("body"); // /获取根节点下的子节点body

			// 遍历body节点

			while (iterss.hasNext()) {
				Element recordEless = (Element) iterss.next();
				String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值

				System.out.println("result:" + result);

				Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form

				// 遍历Header节点下的Response节点

				while (itersElIterator.hasNext()) {

					Element itemEle = (Element) itersElIterator.next();

					String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值

					String subID = itemEle.elementTextTrim("subID");

					System.out.println("banlce:" + banlce);
					System.out.println("subID:" + subID);
					map.put("result", result);
					map.put("banlce", banlce);
					map.put("subID", subID);
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public static void parse(String xml) {
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML

			Element rootElt = doc.getRootElement(); // 获取根节点smsReport

			Iterator iters = rootElt.elementIterator("sendResp"); // 获取根节点下的子节点sms

			while (iters.hasNext()) {
				Element recordEle1 = (Element) iters.next();
				Iterator iter = recordEle1.elementIterator("sms");
				int i = 0;
				// 遍历sms节点

				while (iter.hasNext()) {
					Element recordEle = (Element) iter.next();
					String phone = recordEle.elementTextTrim("phone"); // 拿到sms节点下的子节点stat值
					String smsID = recordEle.elementTextTrim("smsID"); // 拿到sms节点下的子节点stat值
					System.out.println(phone + "===" + smsID);
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// 下面是需要解析的xml字符串例子
		String xmlString = "<html>" + "<head>" + "<title>dom4j解析一个例子</title>"
				+ "<script>" + "<username>yangrong</username>"
				+ "<password>123456</password>" + "</script>" + "</head>"
				+ "<body>" + "<result>0</result>" + "<form>"
				+ "<banlce>1000</banlce>" + "<subID>36242519880716</subID>"
				+ "</form>" + "</body>" + "</html>";
		
		Map map = readStringXmlOut(xmlString);
		Iterator iters = map.keySet().iterator();
		while (iters.hasNext()) {
			String key = iters.next().toString(); // 拿到键

			String val = map.get(key).toString(); // 拿到值

			System.out.println(key + "=" + val);
		}
		
		String xml = "<batchSendResp><sendResp>" +
				"<sms><phone>137000000</phone>" +
				"<smsID>ff8080813349da9001334f0eed8c5923</smsID></sms></sendResp>" +
				"<sendResp><sms><phone>187000000</phone>" +
				"<smsID>ff8080813349da9001334f0eee045924</smsID></sms>" +
				"</sendResp></batchSendResp>";
		/*String xml = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><upomp version='1.0.0' application='TransNotify.Req'>" +
				"<transType>01</transType><merchantId>898000000000002</merchantId><merchantOrderId>839381060965</merchantOrderId>" +
				"<merchantOrderAmt>300</merchantOrderAmt><settleDate>0912</settleDate><setlAmt>300</setlAmt>" +
				"<setlCurrency>156</setlCurrency><converRate></converRate><cupsQid>201409122010035668812</cupsQid>" +
				"<cupsTraceNum>566881</cupsTraceNum><cupsTraceTime>20140912201003</cupsTraceTime><cupsRespCode>00</cupsRespCode>" +
				"<cupsRespDesc>Success!</cupsRespDesc>" +
				"<sign>PlATaDMOAS/QD1PuBRMIisyx3uRMHJ83fHY+xLuGEDkljGJNfGQeEhJO/fLL0zlirWVu5sKZ7GGLsaiKIt6zO9WU5QWSy2kYL5Pg0DqVwwqEn/IrKX1wzQ45W6rXl9DKAxMDnG+CA2JX8Ilm0iZ2IjqmT9Lks1qdMsUjiZZH2fs=</sign>" +
				"<respCode></respCode></upomp>";*/
		parse(xml);
	}

}

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

zhangxj_jack

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值