使用WebService傳遞XML格式的字串作為入參時的工具類
阿新 • • 發佈:2018-12-20
在使用webservice的時候,我們有時候需要使用XML格式來進行傳遞入參或者是出參,那麼入參格式怎麼來進行拼接呢?
請看
/** * @Author: yld * @Date: 2018-12-03 10:36 * @Version 1.0 */ public class XmlUtils { public static String lt = "<"; public static String ltEnd = "</"; public static String rt = ">"; public static String rhtEnd = "/>"; public static String quotes = "\""; public static String equal = "="; public static String blank = " "; /** * @category 拼接xml個元素資訊 * @param element * @return */ public static StringBuffer elementToXml(Element element){ StringBuffer result = new StringBuffer(); //元素開始 result.append(lt).append(element.getName()); //判斷是否有屬性 if (element.getProperty() != null && element.getProperty().size() > 0){ Iterator<String> iterator = element.getProperty().keySet().iterator(); while (iterator.hasNext()){ String key = String.valueOf(iterator.next()); String value = element.getProperty().get(key); result.append(blank).append(key).append(equal).append(quotes).append(value).append(quotes).append(blank); } } //結束的標記 result.append(rt); /** * 判斷是否是葉子節點,如果是葉子節點,需要新增節點內容,不是葉子節點,那麼迴圈新增子節點 */ if (element.isIsleaf()){ result.append(element.getNodeText()); }else { for (Element temp : element.getChild()) { result.append(elementToXml(temp)); } } //元素結束 result.append(ltEnd).append(element.getName()).append(rt); return result; } /** * 拼接xml申明資訊 * @param element * @return */ public static String element2XML(Element element){ StringBuffer body = elementToXml(element); StringBuffer head = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); head.append(body); return head.toString(); } }
接下來給你個使用案例來
Element hosdata = new Element("hosdata"); Element body = new Element("body"); Element cardNo = new Element("cardNo"); cardNo.setNodeText("WX180001"); Element name = new Element("name"); name.setNodeText("張三"); Element sex = new Element("sex"); sex.setNodeText("男"); Element birthDate = new Element("birthDate"); birthDate.setNodeText("1980-08-08"); Element idNo = new Element("idNo"); idNo.setNodeText("35072419800808xxxx"); Element phone = new Element("phone"); phone.setNodeText("13800138000"); Element address = new Element("address"); address.setNodeText("河北省承德市灤平縣"); body.addChild(cardNo); body.addChild(name); body.addChild(sex); body.addChild(birthDate); body.addChild(idNo); body.addChild(phone); body.addChild(address); hosdata.addChild(body); String result = XmlUtils.element2XML(hosdata);
打印出來的xml格式就是這個樣子滴
<?xml version="1.0" encoding="utf-8"?> <hosdata> <body> <cardNo>WX180001</cardNo> <name>張三</name> <sex>男</sex> <birthDate>1980-08-08</birthDate> <idNo>35072419800808xxxx</idNo> <phone>13800138000</phone> <address>xxxxxx</address> </body> </hosdata>
打印出來的字串,看起來很長,實際上轉換出來沒有那麼的多,