java解析url的xml文件,熟悉用Java解析XML文件

Given this XML file:

http://www.emp3world.com/to_download.php?id=33254

GET or POST

a=1&b=2&c=3

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 corectly. What should I change in my code so i can have the correct output ?

Thanks.

解决方案

The problem is your characters method. Change its body to

s.append(new String(ch, start, length));

then add this line to the start of startElement

s.setLength(0);

and you should see some output.

Here's what the Java tutorial on SAX has to say about the characters method:

Parsers are not required to return any particular number of characters at one time. A parser can return anything from a single character at a time up to several thousand and still be a standard-conforming implementation. So if your application needs to process the characters it sees, it is wise to have the characters() method accumulate the characters in a java.lang.StringBuffer and operate on them only when you are sure that all of them have been found.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值