簡體   English   中英

如何使用SAXParser解析XML文件並使用Java將其轉換為Nodelists

[英]How to parse XML file using SAXParser and convert it to Nodelists using Java

我是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 + "  ");

    }
}

一種常用的方法是使用Stack和當前節點的概念。 當遇到startElement請執行以下操作

  1. 創建一個新的child元素
  2. 將此child元素添加到current元素
  3. current元素壓入堆棧
  4. 使child元素成為新的current元素。

當遇到endElement您要進行相反的操作:

  1. stack彈出頂部元素,然后再次創建current元素。

堆棧的底部是root

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM