java之XML
阿新 • • 發佈:2017-11-21
+= sta text eve input key cep numeric parser
1 //轉為XML格式 2 public static String ArrayToXml(Map<String, String> arr) { 3 String xml = "<xml>"; 4 Iterator<Entry<String, String>> iter = arr.entrySet().iterator(); 5 while (iter.hasNext()) { 6 Entry<String, String> entry = iter.next();7 String key = entry.getKey(); 8 String val = entry.getValue(); 9 if (IsNumeric(val)) { 10 xml += "<" + key + ">" + val + "</" + key + ">"; 11 } else 12 xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";13 } 14 xml += "</xml>"; 15 return xml; 16 } 17 18 public static boolean IsNumeric(String str) { 19 if (str.matches("\\d *")) { 20 return true; 21 } else { 22 return false; 23 } 24 }
1 //解析XML 2 privateMap<String, String> doXMLParse(String xml) 3 throws XmlPullParserException, IOException { 4 5 InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); 6 7 Map<String, String> map = null; 8 9 XmlPullParser pullParser = XmlPullParserFactory.newInstance() 10 .newPullParser(); 11 12 pullParser.setInput(inputStream, "UTF-8");// 為xml設置要解析的xml數據 13 14 int eventType = pullParser.getEventType(); 15 16 while (eventType != XmlPullParser.END_DOCUMENT) { 17 switch (eventType) { 18 case XmlPullParser.START_DOCUMENT: 19 map = new HashMap<String, String>(); 20 break; 21 22 case XmlPullParser.START_TAG: 23 String key = pullParser.getName(); 24 if (key.equals("xml")) 25 break; 26 String value = pullParser.nextText(); 27 map.put(key, value); 28 break; 29 case XmlPullParser.END_TAG: 30 break; 31 } 32 eventType = pullParser.next(); 33 } 34 return map; 35 }
java之XML