1. 程式人生 > >Soap報文解析

Soap報文解析

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;

@SuppressWarnings("rawtypes")
public class SoapXmlUtil {
	public Map<String, String> map = new HashMap<String, String>();

	public Map<String, String> ParseSoapXml(String SoapXml) {
		try {
			Document document = DocumentHelper.parseText(SoapXml);
			Element elements = document.getRootElement();
			Iterator iterators = elements.elementIterator();
			// 獲取根節點中的資訊
			while (iterators.hasNext()) {
				Element element = (Element) iterators.next();
				String name = element.getName();
				// 一般Header節點中是空的
				if (name.equals("Body")) {
					Iterator iterator = element.elementIterator();
					this.ParseDom(iterator);
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}
	// 獲取具體key-value
	private void ParseDom(Iterator iterators) {
		while (iterators.hasNext()) {
			Element element = (Element) iterators.next();
			Iterator iterator = element.elementIterator();
			if (iterator.hasNext()) {
				this.ParseDom(iterator);
			} else {
				String key = element.getName();
				String value = element.getStringValue();
				map.put(key, value);
			}
		}
	}
}