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