1. 程式人生 > >axis呼叫webservice 返回xml解析

axis呼叫webservice 返回xml解析

本文轉載 http://lililucky1211.iteye.com/blog/1942222

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

public class Test3 {
	
	public static void main(String[] args) {
		System.out.println("================++++++++++===========");
		try {
			Service service = new Service();
			String url = "http://*****:8004/bianmin.asmx";
			System.out.println("DMZ-url=========="+url);
			String soapaction = "http://www.bluebutterfly.cn/";
			String funcname = "ShowInfoByCardIDName";
			Call call = (Call) service.createCall();
			call.setTargetEndpointAddress(url);
			call.setOperationName(new QName(soapaction, funcname)); // 設定要呼叫哪個方法
			call.addParameter(
					new QName(soapaction, "name"), // 設定要傳遞的引數
					org.apache.axis.encoding.XMLType.XSD_STRING,
					javax.xml.rpc.ParameterMode.IN);
			call.addParameter(
					new QName(soapaction, "cardID"), // 設定要傳遞的引數
					org.apache.axis.encoding.XMLType.XSD_STRING,
					javax.xml.rpc.ParameterMode.IN);
			call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 返回型別

			call.setUseSOAPAction(true);
			call.setSOAPActionURI(soapaction + funcname);
			String uname  = "*濤";
			String cardID = "37***11";
			String v = (String) call.invoke(new Object[] { uname, cardID});// 呼叫方法並傳遞引數
			System.out.println(v);
			System.out.println(xmlElements(v));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
	}
	
	/**
	 * 解析xml字串返回一個Map
	 * 
	 * @param xmlDoc
	 * @return Map
	 */
	public static Map xmlElements(String xmlDoc) {
		Map map = new HashMap();
		// 建立一個新的字串
		StringReader read = new StringReader(xmlDoc);
		// 建立新的輸入源SAX 解析器將使用 InputSource 物件來確定如何讀取 XML 輸入
		InputSource source = new InputSource(read);
		// 建立一個新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();
		try {
			// 通過輸入源構造一個Document
			Document doc = sb.build(source);
			// 取的根元素
			Element root = doc.getRootElement();
			// 得到根元素所有子元素的集合
			List jiedian = root.getChildren();
			// 獲得XML中的名稱空間(XML中未定義可不寫)
			Element et = null;
			for (int i = 0; i < jiedian.size(); i++) {
				et = (Element) jiedian.get(i);// 迴圈依次得到子元素
				map.put(et.getName(), et.getText());
			}
		} catch (JDOMException e) {
			e.printStackTrace();
			System.out.println("出錯");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("出錯");
		}
		read.close();
		return map;
	}
}