1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ParserXMLHandler extends DefaultHandler {
private Tag xmlDocument;
private Map<Integer, Tag> tagPile = new HashMap<Integer, Tag>();
private Integer currentLevel = 0;
private StringBuffer buffer;
@Override
public void processingInstruction(String target, String data) throws SAXException {
super.processingInstruction(target, data);
}
public ParserXMLHandler() {
super();
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
xmlDocument = new Tag();
}
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
buffer = new StringBuffer();
Tag currentTag = new Tag();
currentTag.localName = localName;
for(int i = 0; i < attributes.getLength(); i++){
currentTag.attributes.put(attributes.getLocalName(i), attributes.getValue(i));
}
tagPile.put(this.currentLevel, currentTag);
this.currentLevel++;
}
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
currentLevel--;
int parentLevel = currentLevel - 1;
if(parentLevel >= 0){
Tag currentTag = tagPile.get(currentLevel);
if(buffer != null)
currentTag.value = buffer.toString();
Tag parentTag = tagPile.get(parentLevel);
parentTag.children.add(currentTag);
tagPile.remove(parentTag);
tagPile.remove(currentTag);
tagPile.put(parentLevel, parentTag);
buffer=null;
}else{
xmlDocument = tagPile.get(currentLevel);
}
}
public void characters(char[] ch,int start, int length) throws SAXException{
String lecture = new String(ch,start,length);
if(buffer != null) buffer.append(lecture);
}
public Tag getData(){
return xmlDocument;
}
} |
Partager