2012-11-28 65 views

回答

0

公共無效字符(字符[] CH,INT開始,INT長度)拋出的SAXException {
如果(preTag!= NULL){
字符串含量=新的String(CH ,開始,長度);
if(「name」.equals(preTag)){
student.setName(content); (「age」.equals(preTag)){
} else if(「age」.equals(preTag)){
student.setAge(Float.parseFloat(content));
}
}
}

+0

這是不可靠的。許多SAX解析器實現將字符數據分成多個事件,特別是當文本包含字符實體引用時。例如,「a&b」被編碼爲「a」,並且在許多情況下將作爲至少三個字符()事件發送:「a」,「&」,「b」。 –

2

它看起來像你問DOM,SAX沒有。隨着DOM,你會做這樣的事情:

private String getChildNodeContent(Element parentNode, String tagName) { 
    NodeList children = parentNode.getElementsByTagName(tagName); 
    return children.length == 0 ? null : children.item(0).getTextContent(); 
} 
... 
Element student = (Element) childNodeList.item(k); 
String name = getChildNodeContent(student, "name"); 
String grade = getChildNodeContent(student, "grade"); 
String age = getChildNodeContent(student, "age"); 

在SAX,你必須注意的startElement()和endElement()通過尋找你所關心的開始/結束標記,並捕捉人物去()事件來捕獲文本。

private StringBuilder buffer = new StringBuilder(); 

public void startElement(String uri, String lname, String qname, Attributes atts) { 
    buffer.setLength(0); 
} 

public void endElement(String uri, String lname, String qname) { 
    String tag = context.pop(); 
    String contents = buffer.toString(); 
    // Do something interesting with 'contents' for the given tag. 
    buffer.setLength(0); 
} 

public void characters(char[] ch, int start, int len) { 
    buffer.append(ch, start, len); 
} 
相關問題