<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
基于事件驱动的解析接口 SAX (实例三)
最新推荐文章于 2022-05-17 19:53:17 发布