XML转换之路径转报文

	/**
	 * @param elementName
	 *            XMLPath eg root/accounts[2]/account[2]
	 * @param value
	 *            XMLPath Element Value
	 * @param document
	 *            Empty Document Use Add Element
	 * @return document
	 *         <root><accounts/><accounts><account/><account>11</account></accounts></root>
	 */
	@SuppressWarnings("unchecked")
	public Document convertPathToDocument(String elementName, String value, Document document) {
		String[] nameArray = null;
		if (elementName.indexOf("/") > 0) {
			nameArray = elementName.split("/");
		} else {
			nameArray = elementName.substring(1).split("/");
		}
		String s = "";
		for (int i = 0; i < nameArray.length; i++) {
			List<Node> nodes = null;
			if (i == 0) {
				nodes = document.selectNodes(nameArray[i]);
				if (nodes == null || nodes.size() == 0) {
					Element element = document.addElement(nameArray[i]);
					if (nameArray.length < 2) {
						element.setText(value);
					}
				}
				s = nameArray[i];
			} else {
				// First determine whether a node before current node is a loop node, and then
				// get the node.
				Element element = null;
				if (nameArray[i - 1].indexOf("[") > -1) {
					// If it is a loop node, get with num
					int index = Integer.parseInt(nameArray[i - 1].substring(nameArray[i - 1].indexOf("[") + 1,
							nameArray[i - 1].indexOf("]")));
					element = (Element) document.selectNodes(s).get(index - 1);
				} else {
					element = (Element) document.selectSingleNode(s);
				}
				// determine currnet node whether is a loop node
				Element currElement = null;
				if (nameArray[i].indexOf("[") > -1) {
					int index = Integer
							.parseInt(nameArray[i].substring(nameArray[i].indexOf("[") + 1, nameArray[i].indexOf("]")));
					List<Node> list = element.selectNodes(nameArray[i].substring(0, nameArray[i].indexOf("[")));
					if (list.size() <= index) {
						for (int j = 0; j < index; j++) {
							currElement = element.addElement(nameArray[i].substring(0, nameArray[i].indexOf("[")));
						}
					}
					if (i == nameArray.length - 1) {
						currElement.setText(value);
					}
				} else {
					// currnet node is not a loop node
					currElement = (Element) element.selectSingleNode(nameArray[i]);
					if (currElement == null) {
						currElement = element.addElement(nameArray[i]);
						if (i == nameArray.length - 1) {
							currElement.setText(value);
						}
					}
				}
				if (nameArray[i].indexOf("[") > -1) {
					s = s + "/" + nameArray[i].substring(0, nameArray[i].length() - 3);
				} else {
					s = s + "/" + nameArray[i];
				}
			}
		}
		return document;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值