XercesXMLExtractor.java
上传用户:cctqzzy
上传日期:2022-03-14
资源大小:12198k
文件大小:3k
- package chapter9;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.*;
- import java.io.*;
- import org.w3c.dom.Document;
- import org.w3c.dom.NodeList;
- import org.w3c.dom.Element;
- import org.w3c.dom.Node;
- import org.xml.sax.SAXException ;
- public class XercesXMLExtractor {
- public static void main(String[] args) {
- getXmlNodeText("D:\workshop\docs\tree.xml");
- }
- public static void getXmlNodeText(String filename) {
- // 获取DOM对象树的生成器
- DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
- try {
- // 获取 DocumentBuilder实例
- DocumentBuilder builder = builderfactory.newDocumentBuilder();
- File file = new File(filename);
- ////从 XML 文档获取 DOM 文档实例
- Document document = builder.parse(file);
- //获取某节点的集合
- NodeList nodelist = document.getElementsByTagName("item");
- // 获取节点列表的总长度
- int listnum = nodelist.getLength();
- System.out.println("--------节点数量:"+listnum + "--------");
- for (int i = 0; i < listnum; i++) {
- // 获取节点
- Element eltItem = (Element) nodelist.item(i);
- // 获取节点的各项属性
- Node eltTitle = eltItem.getElementsByTagName("title").item(0);
- Node eltLink = eltItem.getElementsByTagName("addr").item(0);
- Node eltDescription = eltItem.getElementsByTagName("description").item(0);
- String title = "";
- if( eltTitle!= null) {
- title = eltTitle.getFirstChild().getNodeValue();
- }
- String link = "";
- if( eltLink!= null) {
- link = eltLink.getFirstChild().getNodeValue();
- }
- String description = "";
- if( eltDescription!= null) {
- description = eltDescription.getFirstChild().getNodeValue();
- }
- // 输出结果
- System.out.print("标题:");
- System.out.println(title);
- System.out.print("链接:");
- System.out.println(link);
- System.out.print("描述:");
- System.out.println(description);
- System.out.println("----------------------------n");
- }
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- } catch (SAXException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }