今天项目有需要对xml进行一些特定的操作,于是写了个小程序
1 /* 2 * param d: our project's color file 3 * param s: the skin package's color file 4 * result: the 'd' color will be replaced 5 */ 6 public void changeColor(String d, String s) 7 { 8 //eg: 9 //String d = "E:/workspace35/Lianluosms/color.xml"; 10 //String s = "E:/workspace35/QiQiuMa/color.xml"; 11 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 12 try 13 { 14 Map<String, String> map_same = new HashMap<String, String>(); 15 DocumentBuilder db = dbf.newDocumentBuilder(); 16 Document doc_default = db.parse(d); 17 Element root_default = doc_default.getDocumentElement(); 18 NodeList nl_default = root_default.getElementsByTagName("color"); 19 Document doc_skin = db.parse(s); 20 Element root_skin = doc_skin.getDocumentElement(); 21 NodeList nl_skin = root_skin.getElementsByTagName("color"); 22 for(int i = 0; i < nl_skin.getLength(); i++) 23 { 24 Element ed = (Element)nl_skin.item(i); 25 map_same.put(ed.getAttribute("name"), ed.getFirstChild().getNodeValue()); 26 } 27 for(int i = 0; i < nl_default.getLength(); i++) 28 { 29 Element ed = (Element)nl_default.item(i); 30 String key = ed.getAttribute("name"); 31 if(map_same.containsKey(key)) 32 { 33 ed.getFirstChild().setNodeValue(map_same.get(key)); 34 map_same.remove(key); 35 } 36 } 37 Iterator<Entry<String, String>> iter = map_same.entrySet().iterator(); 38 while(iter.hasNext()) 39 { 40 Map.Entry<String, String> entry = (Map.Entry<String, String>)iter.next(); 41 String key = entry.getKey(); 42 String value = entry.getValue(); 43 Element color = doc_default.createElement("color"); 44 Attr attr = doc_default.createAttribute("name"); 45 attr.setValue(key); 46 color.setAttributeNode(attr); 47 Text txtco = doc_default.createTextNode(value); 48 color.appendChild(txtco); 49 root_default.appendChild(color); 50 } 51 DOMSource source=new DOMSource(doc_default); 52 StreamResult result = new StreamResult(new File(d)); 53 54 TransformerFactory tff = TransformerFactory.newInstance(); 55 Transformer tf = tff.newTransformer(); 56 tf.transform(source, result); 57 } 58 catch(Exception e) 59 { 60 e.printStackTrace(); 61 } 62}