[英]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
請執行以下操作
child
元素 child
元素添加到current
元素 current
元素壓入堆棧 child
元素成為新的current
元素。 當遇到endElement
您要進行相反的操作:
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.