参考:
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());
}
}