近期整理了以前的代码,将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");
}
}
使用起来就是这样,输出结果如下: