1. 程式人生 > >XML轉換之路徑轉報文

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;
	}