vbx_wx |
07-07-2011 04:37 AM |
Parsing XML using Sax Parser in Java
I'll show the code first:
Code:
class MyHandler extends DefaultHandler {
public void startElement(String namespaceURI, String sName, String qName, Attributes atts) throws SAXException
{
if(qName.equals("command"))
{
System.out.println("wohoo");
}
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
}
public void characters(char[] ch, int start, int length) throws SAXException
{
}
}
public class XMLParser {
String xmlfile = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<root>" +
"<command action=\"send\" id=\"1234\" [reconnect_after = 0] >" +
"<clip id=\"1\">PD94bWwgdmVyc2lvbj0iMS4wIiBlb</clip>" +
"<clip id=\"2\">kjshdf23987iewjfnb892q34qdhadhax</clip>" +
"</command>" +
"</root>";
public static void main(String[] args)
{
MyHandler handler = new MyHandler();
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = saxFactory.newSAXParser();
XMLParser x = new XMLParser();
saxParser.parse(new InputSource(new StringReader(x.xmlfile)), handler);
}
catch(SAXException e) {}
catch(ParserConfigurationException e){}
catch(IOException e){}
}
}
What I am after is to get the string text from the clip tags. But for now I just tested to see if it can finds the command tags and print something if it does. But it doesn't find it. Anyone knows why ?
edit: looks like the xml is not good, i test it with a xml validator:
Code:
Element type "command" must be followed by attribute specifications: ">" or "/>".
|