-- 作者:CSP15740
-- 发布时间:12/3/2010 6:58:00 PM
-- SAX一下问题
import javax.xml.parsers.*; import org.xml.sax.helpers.*; import org.xml.sax.*; import java.io.*; public class sax_3 { public static void main(String args[]) { try { SAXParserFactory factory=SAXParserFactory.newInstance() ; factory.setNamespaceAware (true); SAXParser saxParser=factory.newSAXParser(); MyHandler handler=new MyHandler(); saxParser.parse(new File("1.xml"),handler); } catch(Exception e) { System.out.println(e);} } } class MyHandler extends DefaultHandler { boolean isComputabled=false,math=false,english=false; int count_1=0,count_2=0,count_3=0; float mathSum=0,englishSum=0,sum=0; public void characters(char[] ch,int start,int length) { String text=new String(ch,start,length); if(isComputabled==true) { String str=text.trim(); if(str.length()>0) { int d=Integer.parseInt(str); sum=sum+d; if(math) mathSum=mathSum+d; if(english) englishSum=englishSum+d; isComputabled=false; } } System.out.print(text); } public void startElement(String uri,String localName, String qName,Attributes atts) { String str=null; if(uri.length()>0) str=uri; System.out.print("<"+qName); if(qName.endsWith("月薪")) { count_1 ++; isComputabled=true; } for(int k=0;k<atts.getLength();k++) { System.out.print(" "+atts.getLocalName(k)+"= "); System.out.print("\""+atts.getValue(k)+"\""); if(atts.getValue(k).startsWith("科长")) { math=true; count_2 ++; } if(atts.getValue(k).startsWith("科员")) { english=true; count_3 ++; } } System.out.print(">"); } public void endElement(String uri,String localName,String qName) { System.out.print("</"+qName+">"); } public void endDocument() { System.out.println(" "); System.out.println("人员总数:"+count_1); System.out.println("科长人数:"+count_2); System.out.println("科长人数:"+count_3); System.out.println("工资总额:"+sum); System.out.println("科长工资总额:"+mathSum); System.out.println("科员工资总额:"+englishSum); } } 为什么这样解析 工资总额和科长工资总额都相同啊 怎么处理啊
|