2011-10-11 158 views
0

我想讀在Java中使用SAX的XML文件。我只得到了的endElement輸出,但我無法找出什麼毛病的startElement。SAX解析器不工作

這是我的處理程序:

public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException 
{ 
SAXParserFactory spf = SAXParserFactory.newInstance(); 
    spf.setNamespaceAware(true); 
SAXParser saxParser = spf.newSAXParser(); 
saxParser.parse("http://www.w3schools.com/xml/note.xml", new XMLHandler()); 
} 

我使用W3Schools的一個示例XML文件:

<!-- Edited by XMLSpy® --> 
<note> 
<to>Tove</to> 
<from>Jani</from> 
<heading>Reminder</heading> 
<body>Don't forget me this weekend!</body> 
</note> 

public class XMLHandler extends DefaultHandler { 

public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { 
System.out.println("SAX Event: START ELEMENT[ " + localName + " ]"); 
} 

public void endElement(String namespaceURI, String localName, String qName) throws SAXException { 
System.out.println("SAX Event: END ELEMENT[ " + localName + " ]"); 
} 

}

我用下面的代碼測試

和T他是我的輸出:

SAX Event: END ELEMENT[ to ] 
SAX Event: END ELEMENT[ from ] 
SAX Event: END ELEMENT[ heading ] 
SAX Event: END ELEMENT[ body ] 
SAX Event: END ELEMENT[ note ] 

我真的不明白我在做什麼錯在這裏...

+0

我把它'新的ProtrackXMLHandler()'是一個剪切/粘貼錯誤,或是ProtrackXMLHandler類不同於XMLHandler類嗎? – beny23

+0

更正後在我的帖子 –

回答

2

我的猜測是,你的方法原型是不正確的。這就是爲什麼你應該總是使用@Override註釋。你可能導入了錯誤的Attributes類?

+0

我導入了java.util.jar.Attributes而不是org.xml.sax.Attributes,謝謝 –