1 18 19 package sync4j.syncclient.common; 20 21 import java.util.HashMap ; 22 import java.util.Iterator ; 23 import java.util.Map ; 24 import java.util.Vector ; 25 26 52 53 public class XMLHashMapParser { 54 55 57 private static final String NULL_VALUE = "NULL_VALUE"; 58 59 60 66 public static String toXML(Map values) { 67 StringBuffer sbXml = new StringBuffer ("<RECORD>"); 68 69 Iterator keys = values.keySet().iterator(); 70 String name = null; 71 String value = null; 72 Object objectValue = null; 73 while (keys.hasNext()) { 74 name = (String )keys.next(); 75 objectValue = values.get(name); 76 if (objectValue == null) { 77 value = NULL_VALUE; 78 } else { 79 value = objectValue.toString(); 80 } 81 82 sbXml.append("\n<FIELD>\n<NAME>"); 83 sbXml.append(name); 84 sbXml.append("</NAME>\n<VALUE>"); 85 sbXml.append(value); 86 sbXml.append("</VALUE>\n</FIELD>"); 87 88 } 89 90 sbXml.append("\n</RECORD>"); 91 92 return sbXml.toString(); 93 } 94 95 101 public static Map toMap(String xml) throws IllegalStateException { 102 Map values = new HashMap (); 103 104 String record = getTagContent(xml, "RECORD"); 105 106 if (record == null) { 107 throw new IllegalStateException ("Bad xml rappresentation"); 108 } 109 110 Vector fields = getListTagContent(record, "FIELD"); 111 String field = null; 112 String name = null; 113 String value = null; 114 115 int numFields = fields.size(); 116 for (int i=0; i<numFields; i++) { 117 field = (String )fields.elementAt(i); 118 name = getTagContent(field, "NAME"); 119 value = getTagContent(field, "VALUE"); 120 121 values.put(name, value); 122 } 123 124 return values; 125 } 126 127 135 private static Vector getListTagContent(String xml, String tag) { 136 Vector tagsContent = new Vector (); 137 138 String startTag = "<" + tag + ">"; 139 String endTag = "</" + tag + ">"; 140 141 int indexStartTag = 0; 142 int indexEndTag = 0; 143 144 String tagContent = null; 145 146 while ( (indexStartTag = xml.indexOf(startTag, indexEndTag)) != -1 ) { 147 indexEndTag = xml.indexOf(endTag, indexStartTag); 148 149 if (indexEndTag == -1) { 150 break; 152 } 153 154 if (indexStartTag == -1 || indexEndTag == -1) { 155 return tagsContent; 156 } 157 158 tagContent = xml.substring(indexStartTag, indexEndTag); 159 tagsContent.addElement(tagContent); 160 161 } 162 return tagsContent; 163 } 164 165 171 private static String getTagContent(String xml, String tag) { 172 String startTag = "<" + tag + ">"; 173 String endTag = "</" + tag + ">"; 174 int indexStartTag = xml.indexOf(startTag) + startTag.length(); 175 int indexEndTag = xml.indexOf(endTag); 176 177 if (indexStartTag == -1 || indexEndTag == -1) { 178 return null; 179 } 180 181 return xml.substring(indexStartTag, indexEndTag); 182 183 } 184 185 186 } | Popular Tags |