📄 bookcounter.java
字号:
import org.xml.sax.*;
import org.xml.sax.helpers.ParserFactory;
import java.io.*;
import org.xml.sax.Parser;
import com.sun.xml.parser.*;
import java.util.*;
public class BookCounter extends HandlerBase
{
private int count=0;
private double totalPrice=0.0;
private StringBuffer content=new StringBuffer();
private Locator locator;
private Stack context= new Stack();
public void BookCount() throws Exception
{
Parser p=ParserFactory.makeParser("com.sun.xml.parser.Parser");
p.setDocumentHandler(this);
p.parse((new File("c:/books.xml")).toURI().toString());
}
public void setDocumentLocator(Locator loc)
{
locator=loc;
}
public void startElement(String name, AttributeList atts) throws SAXException
{
ElementDetails details= new ElementDetails(name,atts);
context.push(details);
//System.out.println("StartElement: ElmentName:"+name);
if(name.equals("book"))
{
if(isFiction())
{
count++;
System.out.println("count="+count);
}
}
}
public void characters(char[] chars,int start, int len) throws SAXException
{
content.append(chars,start,len);
}
public void endElement(String name)throws SAXException
{
if(name.equals("price") && isFiction() && !isVolume())
{
try
{
double price=new Double(content.toString()).doubleValue();
totalPrice+=price;
System.out.println("TotalPrice="+totalPrice);
}
catch(java.lang.NumberFormatException err)
{
if(locator!=null)
{
System.err.println("Error in "+locator.getSystemId()+
"at lint "+locator.getLineNumber()+
"at colume "+locator.getColumnNumber());
}
throw new SAXException("Price is not numberic",err);
}
}
content.setLength(0);
context.pop();
}
public void endDocument() throws SAXException
{
System.out.println("The average price of fiction books is "+totalPrice/count);
System.out.println("There are "+count+" books");
}
public static void main(String args[]) throws Exception
{
(new BookCounter()).BookCount();
}
private boolean isFiction()
{
boolean test = false;
for(int p=context.size()-1;p>=0;p--)
{
ElementDetails elem = (ElementDetails)context.elementAt(p);
if(elem.name.equals("book")&&elem.attributes.getValue("category")!=null &&
elem.attributes.getValue("category").equals("fiction"))
{
System.out.println("-----------------------------------");
return true;
}
}
return false;
}
private boolean isVolume()
{
boolean test = false;
for(int p=context.size()-1;p>=0;p--)
{
ElementDetails elem = (ElementDetails)context.elementAt(p);
if(elem.name.equals("volume"))
{
return true;
}
}
return false;
}
private class ElementDetails
{
public String name;
public AttributeList attributes;
public ElementDetails(String name,AttributeList atts)
{
this.name=name;
this.attributes = new org.xml.sax.helpers.AttributeListImpl(atts);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -