Given this XML file:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<data>
<track clipid="1">
<url>http://www.emp3world.com/to_download.php?id=33254</url>
<http_method>GET or POST</http_method>
<post_body>a=1&b=2&c=3</post_body>
</track>
</data>
</root>
What I am after is to print something like this from this XML file:
ID: 1
URL: http://www.emp3world.com/to_download.php?id=33254
Http method: GET or POST
At the moment this is my primitive handler code:
class MyHandler extends DefaultHandler
{
String str = "";
StringBuilder s = new StringBuilder();
public void startElement(String namespaceURI, String sName, String qName, Attributes atts)
{
if(qName.equals("track"))
{
s.append("ID: ").append(atts.getValue("clipid")).append("\n");
}
if(qName.equals("url"))
{
s.append("URL: ");
}
if(qName.equals("http_method"))
{
s.append("Http method: ");
}
}
public void endElement(String uri, String localName, String qName)
{
if(qName.equals("url"))
{
s.append(str).append("\n");
str = "";
}
if(qName.equals("http_method"))
{
s.append(str).append("\n");
str = "";
}
System.out.println(s);
}
public void characters(char[] ch, int start, int length) throws SAXException {
str = new String(ch, start, length);
}
}
My problem is that it always prints the results 4 times(first time without the Http Method field. I guess this is a problem for all Sax Parsers beginners.
I know what startElement, endElement, characters functions do, but as you can see, I don’t know how to use them correctly. What should I change in my code so I can have the correct output?
The problem is your characters method. Change its body to
then add this line to the start of startElement
and you should see some output.
Here’s what the Java tutorial on SAX has to say about the characters method: