JAVA_SAX\DOM 解析

参考:
https://blog.csdn.net/lsylsy726/article/details/80686761
https://www.cnblogs.com/zyxsblogs/p/10108616.html
https://www.cnblogs.com/loaderman/p/9996343.html

<!-- 利用 SAX 或者 DOM 解析方法求图书价格总和 -->
<?xml version="1.0" encoding="utf-8" >
<booklist>
	<item>
		<price currency="usd">43.56</price>
	</item>
	<! -- 省略余下项 -->
</booklist>
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class MyDOM {
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//利用DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder(); 	//利用Builder
            Document doc = builder.parse("src/data.xml");       	//读取文件
            NodeList nodelist = doc.getElementsByTagName("item");   	//寻找节点

            double sum = 0d;
            for(int i = 0; i < nodelist.getLength(); i++){
                sum += Double.parseDouble(doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue());
            }
            
            System.out.println(sum);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;

public class MySAX extends DefaultHandler {

    private String nodeName;

    private double sum;

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if("price".equals(nodeName)){
            String price = new String(ch, start, length);
            sum += Double.parseDouble(price);
        }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        nodeName = localName;
    }

    public static void main(String[] args) throws Exception {
        //1.创建SAXParser对象
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

        //2.调用parse方法
        parser.parse(new File("./src/data.xml"), new MySAX());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值