代碼學(xué)著視頻敲得,怎么運行結(jié)果就是不一樣呢?
package com.fwh.handle;
import javax.xml.stream.events.StartElement;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class Handletest extends DefaultHandler {
?int index=0;
?//遍歷XML文件的開始標(biāo)簽
?@Override
?public void startElement(String uri, String localName, String qName,
???Attributes attributes) throws SAXException {
??// TODO Auto-generated method stub
??//條用DefaultHandler的startElement方法
??super.startElement(uri, localName, qName, attributes);
???if(qName.equals("book")) {
????index++;
????System.out.println("===========第"+index+"本書開始了============");
//????String a=attributes.getValue("id");
//????System.out.print("屬性名ID的值為:"+a);
????int a=attributes.getLength();
????for(int i=0;i<a;i++) {
?????System.out.print("屬性名:"+attributes.getQName(i));
?????System.out.println("---值為:"+attributes.getValue(i));
????}
???}else if(!qName.equals("book")&&!qName.equals("bookstore")) {
????System.out.print("節(jié)點名是:"+qName);
???}
?}
?//遍歷XML文件的結(jié)束標(biāo)簽
?@Override
?public void endElement(String uri, String localName, String qName)
???throws SAXException {
??// TODO Auto-generated method stub
??super.endElement(uri, localName, qName);
??if(qName.equals("book")) {
??System.out.println("===========第"+index+"本書結(jié)束了============");
??}
?}
?//用來標(biāo)識解析開始
?@Override
?public void startDocument() throws SAXException {
??// TODO Auto-generated method stub
??super.startDocument();
??System.out.println("現(xiàn)在,解析xml開始了!");
?}
?//用來標(biāo)識解析結(jié)束
?@Override
?public void endDocument() throws SAXException {
??// TODO Auto-generated method stub
??super.endDocument();
??System.out.println("現(xiàn)在,解析xml結(jié)束了!");
?}
?@Override
?public void characters(char[] ch, int start, int length) throws SAXException {
??// TODO Auto-generated method stub
??super.characters(ch, start, length);
??String a=new String(ch, start, length);
??if(!a.trim().equals(" ")) {
???System.out.println("---屬性值為:"+a);
??}
?}
}
2018-10-30
大哥啊~equals("")是等于空字符串,不是等于空格~
2018-07-19
1樓是對的.
2018-02-05
判斷寫錯了,是“”,而不是“ ”,中間沒有空格。
你可以輸出ch看一下它的結(jié)構(gòu),他是由一推空格和一堆標(biāo)記還有文字組成,從頭解析,遇到標(biāo)記理解為一組,遇到一堆空格理解為一組,現(xiàn)在是要排除掉空格組,以免錯誤輸出或者null執(zhí)行。String.trim()是去掉首尾所有的空格,一堆空格去掉了所有的空格當(dāng)然就沒有東西了,所以是“”!,判斷中用了(!非),也就是,不是沒有內(nèi)容的字符,剩下的當(dāng)然就是有效的(需要的)了。
2018-01-31
你的屬性值沒有打印出來,a的值是空的,?說明String a=new String(ch, start, length) 這一句有問題,檢查一下char[] 數(shù)組里面的東西,實體類里面有沒有set get,