首页 > 编程语言 > 详细

java之XML

时间:2017-11-21 13:34:54      阅读:189      评论:0      收藏:0      [点我收藏+]
 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         private Map<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

原文:http://www.cnblogs.com/xjbBill/p/7872217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!