1. 程式人生 > >實現將xml與Map互相轉換的方法

實現將xml與Map互相轉換的方法

1 使用vtd技術將xml轉換為Map

    1)引入maven依賴:

        <dependency>
            <groupId>com.ximpleware</groupId>
            <artifactId>vtd-xml</artifactId>
            <version>2.13</version>

        </dependency>

   2)轉換過程:

package com.wj.business.util;
import com.ximpleware.*;
import java.io.UnsupportedEncodingException; import java.util.HashMap; public class ClientResponseUtil2 { private static final String UTF8 = "UTF-8"; public static void main(String args[]) throws UnsupportedEncodingException, ParseException, XPathParseException, NavException, XPathEvalException { String resourceXml = "<?xml version=
\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n" + "<resources>\n" + " <string name=\"January\">January</string>\n" + " <string name=\"February\">February</string>\n" + " <string name=\"March\"
>March</string>\n" + " <string name=\"April\">April</string>\n" + " <string name=\"May\">May</string>\n" + " <string name=\"June\">June</string>\n" + " <string name=\"July\">July</string>\n" + " <string name=\"August\">August</string>\n" + " <string name=\"September\">September</string>\n" + " <string name=\"October\">October</string>\n" + " <string name=\"November\">November</string>\n" + " <string name=\"December\">December</string>\n" + " <string name=\"Today\">Today</string>\n" + " <string name=\"Tomorrow\">Tomorrow</string>\n" + "\n" + "</resources>"; VTDGen vg = new VTDGen(); vg.setDoc(resourceXml.getBytes(UTF8)); vg.parse(false); VTDNav vn = vg.getNav(); //利用AutoPilot進行節點遍歷 AutoPilot ap = new AutoPilot(); int i = -1; ap.bind(vn); ap.selectXPath("/resources"); HashMap<String, Object> map = new HashMap<String, Object>(); while ((i = ap.evalXPath()) != -1) { if (vn.toElement(VTDNav.FIRST_CHILD)) { do { if (vn.getText()!=-1){ map.put(vn.toString(vn.getAttrVal("name")), vn.toString(vn.getText())); } } while (vn.toElement(VTDNav.NEXT_SIBLING)); } vn.toElement(VTDNav.PARENT); } System.out.println(map); } }

使用的xml為:<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
    <string name="January">January</string>
    <string name="February">February</string>
    <string name="March">March</string>
    <string name="April">April</string>
    <string name="May">May</string>
    <string name="June">June</string>
    <string name="July">July</string>
    <string name="August">August</string>
    <string name="September">September</string>
    <string name="October">October</string>
    <string name="November">November</string>
    <string name="December">December</string>
    <string name="Today">Today</string>
    <string name="Tomorrow">Tomorrow</string>

</resources>

說明:這個例子取的是元素的具體的值,也可以通過方法:

vn.toString(vn.getCurrentIndex())(獲取具體標籤的值)替換程式碼中的 vn.toString(vn.getAttrVal("name"))(獲取name元素內容)來獲取到元素的Key值,來解析格式為"<name>wj</name><age>18</age>"的xml.

2 將Map轉換為xml格式(與上述操作可逆)

import java.util.*;
public class Test {
    public static String callMapToXML(Map map) {
        StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?><resources>");
mapToXMLTest2(map, sb);
sb.append("</resources>");
        return sb.toString();
}

    private static void mapToXMLTest2(Map map, StringBuffer sb) {
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
Object value = map.get(key);
            if (null == value)
                value = "";
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
mapToXMLTest2(hm, sb);
}
                sb.append("</" + key + ">");
} else {
                if (value instanceof HashMap) {
                    sb.append("<" + key + ">");
mapToXMLTest2((HashMap) value, sb);
sb.append("</" + key + ">");
} else {
                    /*返回這種格式的xml會直接執行如下程式碼*/
sb.append("<String name=\"" + key + "\">" + value + "</String>");
}

            }

        }
    }
    public static void main(String args[]){
        Map<String,Object> map =new HashMap<String, Object>();
map.put("app_name","testApp");
map.put("search_label","Dictionary");
map.put("search_hint","Search the dictionary");
String ss = Test.callMapToXML(map);
System.out.println(ss);
}

}