class="xml" name="code"><?xml version="1.0" encoding="UTF-8"?> <root> <var> <name>logo_src</name> <value>images/logo.gif</value> </var> <var> <name>logo_src1</name> <value>images/logo.gif111</value> </var> <var> <name>logo_src2</name> <value>images/logo.gif222</value> </var> <var> <name>logo_src3</name> <value>images/logo.gif333</value> </var> <var> <name>logo_src4</name> <value>images/logo.gif444</value> </var> </root>
?
?读取XML文件的全部值
private Vector readXMLFile(String file) throws Exception {//测试通过 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(file); // 获取到xml文件 // 开始读取 Element root = doc.getDocumentElement(); // 获取根元素 NodeList vars = root.getElementsByTagName("var"); info_Vector = new Vector(); for (int i = 0; i < vars.getLength(); i++) { // 一次取得每一个元素 info info = new info(); Element element = (Element) vars.item(i); NodeList names = element.getElementsByTagName("name"); Element element1 = (Element) names.item(0); Node node1 = element1.getFirstChild(); info.setName(node1.getNodeValue());//取得name字段的值 NodeList value = element.getElementsByTagName("value"); Element element2 = (Element) value.item(0); Node node2 = element2.getFirstChild(); info.setValue(node2.getNodeValue());//取得value字段的值 info_Vector.add(info); } return info_Vector; }
?向XML文件添加值
public static void addXmlCode(String file, String name, String value) { //测试通过 try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(file); // 获取到xml文件 //builder = factory.newDocumentBuilder(); //Document doc = builder.parse(path); doc.normalize(); Text textseg; Element var = doc.createElement("var"); Element name1 = doc.createElement("name"); textseg = doc.createTextNode(name); name1.appendChild(textseg); var.appendChild(name1); Element name2 = doc.createElement("value"); textseg = doc.createTextNode(value); name2.appendChild(textseg); var.appendChild(name2); doc.getDocumentElement().appendChild(var); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer; transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new java.io.File(file)); transformer.transform(source, result); } catch (Exception e) { } }
?