09/16 JavaWeb系統學習 XML的讀取及其解析
阿新 • • 發佈:2018-12-10
初學:
需要用到的工具:dom4j.jar
讀取xml檔案:(匯入的都是org.w3c.dom下的包)
基於DocumentBuilderFactory
DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance(); DocumentBuilder newDocumentBuilder = newInstance.newDocumentBuilder(); Document parse = newDocumentBuilder.parse("src/person.xml"); NodeList elementsByTagName = parse.getElementsByTagName("name"); for(int i=0;i<elementsByTagName.getLength();i++){ Node name1 = elementsByTagName.item(i); String names = name1.getTextContent(); System.out.println(names); }
回寫xml檔案:
Node item = parse.getElementsByTagName("person").item(0); Element createElement = parse.createElement("subject"); Text createTextNode = parse.createTextNode("software engineering"); createElement.appendChild(createTextNode); item.appendChild(createElement); TransformerFactory newInstance2 = TransformerFactory.newInstance(); Transformer newTransformer = newInstance2.newTransformer(); newTransformer.transform(new DOMSource(parse), new StreamResult("src/person.xml"));
基於TransformerFactory