最近工做涉及到對xml文件的操做,記點心得。html
java能夠有四種方法操做xml文件,我採用了dom方式,跟js中對html元素的操做有些相似。java
用到的jar包:http://download.csdn.net/detail/sdsky1987/4083634node
讀取xml文件:數組
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document document = db.parse("c:\\test.xml");
增長節點root並賦屬性code, locale, version。添加子節點child, 併爲子節點賦值"text":app
org.w3c.dom.Element root = document.createElement("root"); root.setAttribute("code", code); root.setAttribute("locale", locale); root.setAttribute("version", getCapVersion()); document.appendChild(root); org.w3c.dom.Element child = document.createElement("child"); Text nameValue = doc.createTextNode("text"); root.appendChild(child); child.appendChild(value);
修改第一個root節點的屬性值code爲"code modified"(注:getElementsByTagName取出來的是一個節點數組):dom
NodeList nodelList = document.getElementsByTagName("root"); Element element = (Element) nodeList.item(0); String code = element.getAttribute("code"); if(code != null){ element.setAttribute("code", "code modified"); }
修改全部child節點的值爲"new text"(標籤對裏面的內容):ui
NodeList nodeList = document.getElementsByTagName("child"); for(int i = 0; i < nodeList.getLength(); i++){ Element element = (Element) nodeList.item(i); element.setTextContent("new text"); }
刪除root節點屬性locale,刪除子節點child:編碼
NodeList nodeList = document.getElementsByTagName("root"); for(int i = 0; i < nodeList.getLength(); i++){ Element element = (Element) nodeList.item(i); element.removeAttribute("locale"); NodeList childNodeList = element.getElementsByTagName("child"); nodeList.removeChild(childNodeList.item(0)); }
最後做完修改,別忘記保存test.xml:.net
TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domsource = new DOMSource(document); //設置編碼,換行,縮進 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperty(OutputKeys.INDENT,"yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); //保存xml StreamResult result = new StreamResult("C:\\test.xml"); transformer.transform(domsource, result);