这是我通过正则表达式实现的xml文件解析工具,有些XHTML文件中包含特殊符号,暂时还无法正常使用。
设计思路:常见的xml文件都是单根树结构,工具的目的是通过递归的方式将整个文档树装载进一个Node对象。xml文档树上的每一个节点都能看做一个Node对象,它拥有title、attribute和text三个自身变量以及一个childrenNode集合用来存放子节点,使用正则表达式完整装载。
一、编写Node类
Node对象是文档解析的基础,最终可以通过对象的不同属性实现对文档信息的访问。
import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Node implements Serializable { // 可以对Node对象持久化保存 private static final long serialVersionUID = 1L; private int id; // 节点类型 private String title; // 节点内容 private String text; // 节点属性集合 private Map<String, String> attributes = new HashMap<String, String>(); // 子节点集合 private List<Node> childNodes = new LinkedList<Node>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Map<String, String> getAttribute() { return attributes; } public void setAttribute(Map<String, String> attribute) { this.attributes = attribute; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<Node> getChildNode() { return childNodes; } public void setChildNode(List<Node> childNode) { this.childNodes = childNode; } // 将属性集合转换成一条完整的字符串 private String attrToString() { if (attributes.isEmpty()) { return ""; } Iterator<Entry<String, String>> its = attributes.entrySet().iterator(); StringBuffer buff = new StringBuffer(); while (its.hasNext()) { Entry<String, String> entry = its.next(); buff.append(entry.getKey() + "=\"" + entry.getValue() + "\" "); } return " " + buff.toString().trim(); } // 输出完整的节点字符串也用到了递归 @Override public String toString() { String attr = attrToString(); if (childNodes.isEmpty() && text == null) { return "<" + title + attr + "/>\n"; } else if (childNodes.isEmpty() && text != null) { return "<" + title + attr + ">\n" + text + "\n" + "</" + title + ">\n"; } else { StringBuffer buff = new StringBuffer(); buff.append("<" + title + attr + ">\n"); if (!text.isEmpty()) { buff.append(text + "\n"); } for (Node n : childNodes) { buff.append(n.toString()); } buff.append("</" + title + ">\n"); return buff.toString(); } } }