首先对于XML文件基础解析中说到,获取一个DocumentBuilder只需要执行一次,
但是对于获取XML文件位置需要用户来定。
首先完成XML文件路径的获取:
注意static
public static Document newDocument(String xmlPath)
throws XMLNotFoundException, SAXException, IOException {
InputStream is = Class.class.getResourceAsStream(xmlPath);
if (is == null) {
throw new XMLNotFoundException("XML文件[" + xmlPath + "]不存在。");
}
return newDocument(is);
}
实际就是吧之前4行代码后两行加到这个方法中。
接着对于XML文件重点就是不同Tag的解析:每个Tag解析都是相同的,只是对应的标签名需要改变。
先给出代码:
public abstract void dealElement(Element element, int index) throws Throwable;
public void parseTag(Document document, String tagName) throws Throwable {
NodeList nodeList = document.getElementsByTagName(tagName);
for (int index = 0; index < nodeList.getLength(); index++) {
Element element = (Element) nodeList.item(index);
dealElement(element, index);
}
}
public void parseTag(Element element, String tagName) throws Throwable {
NodeList nodeList = element.getElementsByTagName(tagName);
for (int index = 0; index < nodeList.getLength(); index++) {
Element ele = (Element) nodeList.item(index);
dealElement(ele, index);
}
}
对于根标签和子标签分别使用Document类和Element类
注意这里有一个抽象方法,即这个XMLParser类在实例化时,需要用户来定义这个抽象类。
这样就可以做到根据不同的XML文件内容,有不同的获取方法且该方法由用户来定。
调用方法:
XMLParser xmlParser = new XMLParser() {
@Override
public void dealElement(Element element, int index) throws Throwable { //定义一个标签属性获取的抽象方法
StringBuffer str = new StringBuffer();
String id = element.getAttribute("id");
str.append("id = ").append(id);
String name = element.getAttribute("name");
str.append(", name = ").append(name);
String sex = element.getAttribute("sex");
str.append(", sex = ").append(sex);
String birthday = element.getAttribute("birth");
str.append(", birth = ").append(birthday);
new XMLParser() {
@Override
public void dealElement(Element element, int index) throws Throwable { //子标签获取方法
String hobbyId = element.getAttribute("id");
String hobbyName = element.getTextContent();
str.append("\n\t").append(hobbyId).append(":").append(hobbyName);
}
}.parseTag(element, "hobby"); //匿名对象 直接调用
new XMLParser() {
@Override
public void dealElement(Element element, int index) throws Throwable { //子标签获取方法
String introduceText = element.getTextContent().trim();
str.append("\n简介:").append(introduceText);
}
}.parseTag(element, "introduce"); //匿名对象 直接调用
System.out.println(str);
}
};
Document document = XMLParser.newDocument("/关于XML/student.xml");
xmlParser.parseTag(document, "student"); //根标签的获取
具体解释见注释