基于事件驱动的解析接口 SAX (实例三)

<script type="text/javascript"> google_ad_client = "pub-8800625213955058"; /* 336x280, 创建于 07-11-21 */ google_ad_slot = "0989131976"; google_ad_width = 336; google_ad_height = 280; // </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> 实例三、计算 订单 的 总价格(如何取出正文的值)。 问题:请计算 orders.xml 所示的总价格 orders.xml 的源文件。 <订单> <商品 数量="21"> <名称> 袜子 <单价> 3.24 <商品 数量="1"> <名称> 贝斯 <单价> 4200.00 <商品 数量="5"> <名称> 域名 <单价> 60.50 <商品 数量="2"> <名称> 书 <单价> 99.00 下面的代码使用了 SUN 的 JAXP 包,请在 http://java.sun.com/xml/download.html 下载。 在 Jbuilder4 中运行正确。 import org.xml.sax.*; import javax.xml.parsers.*; import java.util.Vector; /** * Title: XML Study, Sample 3 * Description: Count the Order Sum. * Copyright: Copyright (c) 2001 * Company: Isolation Land. * @author Slepworm * @version 1.0 */ public class CountSum extends org.xml.sax.helpers.DefaultHandler { private double totalPrice = 0.00; private StringBuffer content = new StringBuffer(); private Vector numberV = new Vector(); private Vector priceV = new Vector(); private double totalSum = 0.00; public CountSum() { } public static void main(String[] args) throws Exception { CountSum cs = new CountSum(); cs.createParser(); } public void createParser() throws Exception{ SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(false); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); xr.parse("http://localhost/orders.xml"); } // 取得 商品 中属性 数量 的值,并将它放入数组 numberV 中。 public void startElement(String namespaceURI, String localName, String rawName, Attributes atts) throws SAXException { if (rawName.equals("商品")) { String number = atts.getValue("数量"); numberV.addElement(number); //System.out.println(numberV); } content.setLength(0); } // **** 此方法将遍历 XML 文件,获取 文本 值。 public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); //System.out.println(content.toString()); // 打印出来,看看此方法是怎样运行的 } // **** 仅获取元素 单价 中的文本,并将它放入数组 priceV 中。 public void endElement(String uri, String localName, String qName) throws SAXException { if (localName.equals("单价")) { String price = content.toString(); priceV.addElement(price); //System.out.println(priceV); } } // 计算总价格 public void endDocument() throws SAXException { int num; double pr; for (int i=0; i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值