技術總結:XML檔案解析
阿新 • • 發佈:2018-12-15
近期整理了以前的程式碼,將XML檔案的解析程式碼程式設計了一個工具。通過Document類得到一個NodeList,遍歷其得到標籤,通過標籤得到XML檔案的內容。利用抽象方法提供給使用者處理檔案的介面。程式碼如下:
/* * @auther yc * 2018/10/13 */ package yc_util.core; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public abstract class XMLReader { private static DocumentBuilder documentBuilder; public XMLReader() { } private static void init() { try { documentBuilder = DocumentBuilderFactory .newInstance() .newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } public static Document document(InputStream is) { Document document = null; init(); try { document = documentBuilder.parse(is); } catch (SAXException | IOException e) { e.printStackTrace(); } return document; } public static Document document(String path) { InputStream inputStream = XMLReader.class.getResourceAsStream(path); return document(inputStream); } public abstract void dealElement(Element element, int index); public XMLReader xmlParse(Document document, String tagname) { NodeList nodeList = document.getElementsByTagName(tagname); for(int index = 0; index < nodeList.getLength(); index++) { Element element = (Element) nodeList.item(index); dealElement(element, index); } return this; } public XMLReader xmlParse(Element element, String tagname) { NodeList nodeList = element.getElementsByTagName(tagname); for(int index = 0; index < nodeList.getLength(); index++) { Element ele = (Element) nodeList.item(index); dealElement(ele, index); } return this; } }
現在編寫一個Test測試一下
先編寫一個供測試的XML檔案:
<?xml version="1.0" encoding="UTF-8"?> <bookStory> <book id = "玄幻小說"> <property name = "遮天" author = "辰東" price = "998美刀"></property> <property name = "完美世界" author = "辰東" price = "999美刀"></property> </book> <book id = "文學小說"> <property name = "巴黎聖母院" author = "不知道" price = "太貴了買不起"></property> <property name = "霧都孤兒" author = "真不知道" price = "太貴了嚇死人"></property> </book> </bookStory>
接下來編寫測試類:
/* * @auther yc * 2018/10/13 */ package yc_util.demo; import org.w3c.dom.Element; import yc_util.core.XMLReader; public class XMLReaderDemo { public static void main(String[] args) { new XMLReader() { @Override public void dealElement(Element element, int index) { new XMLReader() { @Override public void dealElement(Element element, int index) { System.out.println("書名 :" + element.getAttribute("name") + " 作者:" + element.getAttribute("author") + " 價格:" +element.getAttribute("price")); } }.xmlParse(element, "property"); } }.xmlParse(XMLReader.document("/config.xml"), "book"); } }
使用起來就是這樣,輸出結果如下: