这篇文章将为大家详细讲解有关Java中的xml文件怎么利用正则表达式进行解析,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、编写Node类
Node对象是文档解析的基础,最终可以通过对象的不同属性实现对文档信息的访问。
Node.java:
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 attributes = new HashMap();
// 子节点集合
private List childNodes = new LinkedList();
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 getAttribute() {
return attributes;
}
public void setAttribute(Map attribute) {
this.attributes = attribute;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List getChildNode() {
return childNodes;
}
public void setChildNode(List childNode) {
this.childNodes = childNode;
}
// 将属性集合转换成一条完整的字符串
private String attrToString() {
if (attributes.isEmpty()) {
return "";
}
Iterator> its = attributes.entrySet().iterator();
StringBuffer buff = new StringBuffer();
while (its.hasNext()) {
Entry 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();
}
}
}