0

我是 SAXParser 的新手,所以请原谅我。

如何解析任何 XML 文件并将其转换为List<XNode>?下面是类 XNode 的结构:

class XNode{

    private String nodeName;
    private String nodeValue;
    private List<XAttribute> attributes;
    private boolean isParentNode;
    private List<XNode> childNodes;
}

还有XAttribute的结构:

class XAttribute{

    private String name;
    private String value;
}

通过解析任何文件,它应该返回 List 对象。

到目前为止,我已经尝试了下面的代码,但不知道如何检查和附加 childNodes。

public class XmlProcesser extends DefaultHandler {
    XMLResponse xmlResponse = null;
    boolean endtag = false;

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        System.out.print("" + qName + "");
        if (attributes.getLength() == 0) {
        } else {
            for (int index = 0; index < attributes.getLength(); index++) {
                System.out.print(attributes.getLocalName(index) + " =  " + attributes.getValue(index));
            }
        }
    }

    @Override
    public void characters(char ch[], int start, int length) throws SAXException {
        String s = new String(ch, start, length);
        System.out.println(s);
        endtag = false;
    }

    @Override
    public void endElement(String uri, String localName,
            String qName) throws SAXException {
        endtag = true;
        System.out.print("  " + qName + "  ");

    }
}
4

2 回答 2

0

一种常用的方法是使用Stack当前节点的 a 和 a 概念。当您遇到 astartElement时,请执行以下操作

  1. 创建一个新元素child
  2. 将此child元素添加到current元素
  3. current元素压入栈中
  4. 使child元素成为新current元素。

当你遇到endElement你做相反的事情:

  1. 从 中弹出顶部元素stack并再次制作该current元素。

堆栈的底部是root.

于 2012-10-09T23:37:24.697 回答
0
Pop the top element from the stack and make the current element again.

Pop the top element from the stack and make the current element again.

Pop the top element from the stack and make the current element again.

Pop the top element from the stack and make the current element again.
于 2013-02-01T12:21:07.003 回答