我正在尝试编写一个xml解析器,非常简单,我需要知道如何在主类中使用这些类从xml文件中执行Tree而不使用DOM或SAX。 我不明白如何使用递归来插入子节点,我的两个类是:
public class XmlNode {
private final String strTag;
private final List<Node> children;
public Node(String strTag) {
this.strTag= strTag;
this.children = new ArrayList<Node>();
}
public String getTagName() {
return strTag;
}
public void addChild(XmlNode child) {
children.add(child);
}
}
public class XmlTree {
private XmlNode root;
public XmlTree() {
this.root = null;
}
public XmlTree(XmlNode root) {
this.root = root;
}
public XmlNode getRoot() {
return root;
}
public void setRoot(XmlNode root) {
this.root = root;
}
public int size() {
int numberOfNodes = 0;
if(root != null) {
numberOfNodes = size(root) + 1; //1 para la raiz
}
return numberOfNodes;
}
private int size(XmlNode node) {
int numberOfNodes = node.getNumberOfChildren();
for(XmlNode child : node.getChildrenNode()) {
numberOfNodes += size(child);
}
return numberOfNodes;
}
}