Fork me on GitHub

Java从零开始学四十二(DOM解析XML)

一、DOM解析XML

 xml文件

favorite.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<PhoneInfo name="手机品牌">
    <Brand name="华为">
        <Type name="U8650">
        </Type>
    </Brand>
    <Brand name="三星">
        <Type name="i9100G">
        </Type>
        <Type name="I9108">
        </Type>
    </Brand>
    <Brand name="Apple">
        <Type name="iPhone4">
        </Type>
    </Brand>
</PhoneInfo>

解析

public static void getItemXML() {
        try {

            // 1.得到DOM解析器的工厂
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            // 2.得到DOM工厂获得DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();

            // 3.解析XML文档,得到一个Document即DOM树
            Document doc = db.parse("xml/favorite.xml");
            // 4.得到所有<Brand>节点列表信息
            NodeList brandList = doc.getElementsByTagName("Brand");
            // 5.循环Brand信息
            for (int i = 0; i < brandList.getLength(); i++) {
                Node brandNode = brandList.item(i);
                // 类型转换
                Element brandElement = (Element) brandNode;
                // 获取Brand的Name属性
                String brandName = brandElement.getAttribute("name");
                System.out.println("手机品牌:" + brandName);
                // 获取Brand的子节点
                NodeList typeList = brandNode.getChildNodes();
                for (int j = 0; j < typeList.getLength(); j++) {
                    // 判断是否为Elemnet 可能有空字符串
                    if (typeList.item(j) instanceof Element) {
                        // 遍历
                        Element typeElement = (Element) typeList.item(j);
                        // 型号
                        String typeName = typeElement.getAttribute("name");
                        // 输出
                        System.out.println("手机型号 :" + typeName);
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

有文本内容的解析

网易手机各地行情.xml--一部分

<?xml version="1.0" encoding="GBK"?><?xml-stylesheet type="text/css" href="http://news.163.com/css/allrss.css"?>
<rss version="2.0">
    <channel>
        <title>网易手机各地行情</title>
        <link>http://tech.163.com/mobile/special/00111SJM/sjhq_gd.html</link>
        <description>全国其他地区手机行情</description>      
        <item>        
            <title><![CDATA[超高性价比智能机 华为 U8650 仅1280元]]></title>        
            <link>http://tech.163.com/mobile/11/1115/12/7ITDEDDA00112K8C.html</link>        
            <description><![CDATA[U8650是华为今年推出的一款3G智能手机,该机搭载Android OS 2.3系统,采用3.5英寸480×320像素的触控屏,内置320万像素CMOS摄像头,还具备双512MB内存,整机性能非常不错。其轻,薄的特点,很适合女性使用。感兴趣的朋友不妨来关注一下吧。近日该机在经销商处有售,售价为880元。                        手机最新价格变动  ]]>......</description>        
            <pubDate>2011-11-25 12:50:46</pubDate>      
        </item>      
        <item>        
            <title><![CDATA[超高性价比智能机 华为 U8650 仅1800元]]></title>        
            <link>http://tech.163.com/mobile/11/1115/12/7ITDEDDA00112K8C.html</link>        
            <description><![CDATA[U8650是华为今年推出的一款3G智能手机,该机搭载Android OS 2.3系统,采用3.5英寸480×320像素的触控屏,内置320万像素CMOS摄像头,还具备双512MB内存,整机性能非常不错。其轻,薄的特点,很适合女性使用。感兴趣的朋友不妨来关注一下吧。近日该机在经销商处有售,售价为880元。                        手机最新价格变动  ]]>......</description>        
            <pubDate>2011-11-20 12:50:46</pubDate>      
        </item>
        <item id="1">
            <title><![CDATA[800万双网双待摩托罗拉XT882卖3950]]></title>
            <link>http://tech.163.com/mobile/11/1115/13/7ITGR17S00112K8C.html</link>
            <description><![CDATA[摩托罗拉XT882是一款支持3G双网双核的智能手机,配备了1G双核Tegra 2处理器、全新的Android 2.3操作系统、4.0英寸qHD高清晰电容屏幕、1080P高清视频播放及输出、8GB超大机身内存……今天小编从卖场商家处获悉,800万双网双待摩托罗拉XT882卖3950元,喜欢的朋友不妨来围观一下吧。在外观上,摩托XT882在外形方面和Atrix 4G基 ]]>......</description>
            <pubDate>2011-11-15 13:50:45</pubDate>
        </item>
        <item id="GUID" read="true">
            <title><![CDATA[感恩节又放价 三星i9100G行货3999元]]></title>
            <link>http://tech.163.com/mobile/11/1115/13/7ITGQV8V00112K8C.html</link>
            <description><![CDATA[三星i9100G是近期上市的一款智能手机,1.2GHz主频双核处理器的加入为整机流畅运行提供了最有利保证,整体表现十分出色。三星i9100G正面搭载一块4.3英寸分辨率为480×800像素触控屏,并且采用了Super AMOLED PLUS材质,无论是色彩饱和度以及艳丽程度都比I9000的Super AMOLED出色。此外,在机身背面它还内置一枚800万像素的摄 ]]>......</description>
            <pubDate>2011-11-15 13:50:45</pubDate>
        </item>
        <item id="3">
            <title><![CDATA[刺激享受 大屏双核机 HTC G19仅3500]]></title>
            <link>http://tech.163.com/mobile/11/1115/12/7ITDEFIP00112K8C.html</link>
            <description><![CDATA[HTC的G系列一直是人们最为关注的,在性能上不断的更新让人们享受到了更为强劲的使用性能。G19是HTC前段时间推出的一款4G智能机,搭载Android OS 2.3系统,采用1536MHz的双核处理器,还配有4.5英寸的触控屏,800万像素摄像头,绝对是一款目前最为强劲的实力机型。感兴趣的朋友不妨来关注一下吧。                            ]]>......</description>
            <pubDate>2011-11-15 12:50:46</pubDate>
        </item>
        <item id="4">
            <title><![CDATA[典雅典范 为时尚代言 索爱X8仅980元]]></title>
            <link>http://tech.163.com/mobile/11/1115/12/7ITDEE6U00112K8C.html</link>
            <description><![CDATA[时尚几乎就是专门为X8而设的词语,它是索尼爱立信推出的一款智能手机,小巧的机身,时尚又不失典雅高端的气质,搭载主流的Android 2.1系统,采用600MHz的高通 MSM7227处理器,还内置了320万像素的摄像头,带来不错的使用体验。感兴趣的朋友不妨来关注一下吧。                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ]]>......</description>
            <pubDate>2011-11-15 12:50:46</pubDate>
        </item>
        <item id="5">
            <title><![CDATA[高性价比智能机 华为 U8650 仅880元]]></title>
            <link>http://tech.163.com/mobile/11/1115/12/7ITDEDDA00112K8C.html</link>
            <description><![CDATA[U8650是华为今年推出的一款3G智能手机,该机搭载Android OS 2.3系统,采用3.5英寸480×320像素的触控屏,内置320万像素CMOS摄像头,还具备双512MB内存,整机性能非常不错。其轻,薄的特点,很适合女性使用。感兴趣的朋友不妨来关注一下吧。近日该机在经销商处有售,售价为880元。                        手机最新价格变动  ]]>......</description>
            <pubDate>2011-11-15 12:50:46</pubDate>
        </item>
    </channel>
</rss>

解析

    public static List<Item> getItems(){

        try {
            
            //创建DocumentBuilderFactory
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            //创建DocumentBuilder
            DocumentBuilder    db = dbf.newDocumentBuilder();
            //创建Documnet
            Document doc=db.parse("xml/网易手机各地行情.xml");
            //获取节点
            NodeList itemList=doc.getElementsByTagName("item");
            for(int i=0;i<itemList.getLength();i++){
                Element item=(Element)itemList.item(i);
                String id=item.getAttribute("id");
                //System.out.println("编号"+id);
                String title=item.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
                String link=item.getElementsByTagName("link").item(0).getFirstChild().getNodeValue();
                String description=item.getElementsByTagName("description").item(0).getFirstChild().getNodeValue();
                String pubDate=item.getElementsByTagName("pubDate").item(0).getFirstChild().getNodeValue();
                //System.out.println("标题:  "+title+"\t\t连接:   "+link+"\t\t描述:  "+description+"\t\t 发布日期:"+pubDate);
            
            }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        

    }

 

二、增加XML

// 增加新的节点 增加小米
    public static void savePhone() {

        try {
            // 1.创建DocumentBuilderFactory
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            // 2.创建DocumentBuilder
            DocumentBuilder db = dbf.newDocumentBuilder();
            // 3.创建Document
            Document doc = db.parse("xml/favorite.xml");
            // 创建新的节点
            Element brandElement = doc.createElement("Brand");
            brandElement.setAttribute("name", "小米");
            // 创建type子节点
            Element typeElement1 = doc.createElement("Type");
            Element typeElement2 = doc.createElement("Type");
            typeElement1.setAttribute("name", "红米");
            typeElement2.setAttribute("name", "米4");
            brandElement.appendChild(typeElement1);
            brandElement.appendChild(typeElement2);
            // 找到根节点
            Element PhoneInfo = (Element) doc.getElementsByTagName("PhoneInfo")
                    .item(0);
            PhoneInfo.appendChild(brandElement);

            // 保存XML
            TransformerFactory trf = TransformerFactory.newInstance();
            Transformer tf = trf.newTransformer();
            // 数据源
            DOMSource ds = new DOMSource(doc);
            // 设置编码类型
            tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            // 设置流
            FileOutputStream fos = new FileOutputStream("xml/favorite.xml");
            StreamResult result = new StreamResult(fos);
            // 把dom树转换为XML
            tf.transform(ds, result);
            fos.close();
            System.out.println("-=========写入完成!==========");

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

    }

 

三、修改节点

// 修改节点将苹果修改为Apple
    public static void modify() {
        try {
            // 创建DocumentBuilderFactory
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            // 创建DocumentBuilder
            DocumentBuilder db = dbf.newDocumentBuilder();
            // 创建Document
            Document doc = db.parse("xml/favorite.xml");
            NodeList brandList = doc.getElementsByTagName("Brand");
            for (int i = 0; i < brandList.getLength(); i++) {
                Element brand = (Element) brandList.item(i);
                String brandName = brand.getAttribute("name");
                // 查找
                if (brandName.equals("苹果")) {
                    // 修改属性
                    brand.setAttribute("name", "Apple");
                }
            }

            // 写入XML
            TransformerFactory trf = TransformerFactory.newInstance();
            Transformer tf = trf.newTransformer();
            DOMSource ds = new DOMSource(doc);
            // 设置流
            FileOutputStream fos = new FileOutputStream("xml/favorite.xml");
            StreamResult result = new StreamResult(fos);
            // 设置编码类型
            tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            // 写入文件
            tf.transform(ds, result);
            fos.close();
            System.out.println("-=========修改完成!==========");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

 

四、删除节点

// 删除Brand name是华为的子节点
    public static void delete(){
        try {
        //创建DocumentBuilerFactory
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //DocumentBuilder
            DocumentBuilder db=dbf.newDocumentBuilder();
        //创建Document
            Document doc=db.parse("xml/favorite.xml");
        //创建Brand节点集合
            NodeList brandList=doc.getElementsByTagName("Brand");
            //遍历
            for (int i = 0; i < brandList.getLength(); i++) {
                Element brandElement=(Element) brandList.item(i);
                String name=brandElement.getAttribute("name");
                if(name.equals("华为")){
                    //获取父节点,使用父节点删除这个节点
                    brandElement.getParentNode().removeChild(brandElement);
                }
            }
            //写入XML
            TransformerFactory trf=TransformerFactory.newInstance();
            Transformer tf=trf.newTransformer();
            //数据源
            DOMSource ds=new DOMSource(doc);
            //设置流
            FileOutputStream fos=new FileOutputStream("xml/favorite.xml");
            StreamResult result=new StreamResult(fos);
            //设置编码格式
            tf.setOutputProperty(OutputKeys.ENCODING,"utf-8");
            //写入文件
            tf.transform(ds, result);
            fos.close();
            
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

 五、更新RSS

package com.pb.biz;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class DownloadRSSBiz {
    /**
     * 下载RSS
     * @param url
     */
    public void downloadRSS(String url){
        try {
            // 发帖机原理,模拟浏览器
            // final String SERVER_URL =
            // "http://10.0.0.131/mobile/special/001144R8/gedihangqing.xml"; //
            // 定义需要获取的内容来源地址

            URL uri = new URL(url);
            URLConnection con = uri.openConnection();
            con.setDoOutput(true);
            //设置请求参数
            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");

            //取返回值
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream(), "GBK"));
            StringBuilder sBuilder = new StringBuilder();
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                sBuilder.append(line);
            }
            //存入文件
            FileWriter writer = new FileWriter("src/网易手机各地行情.xml", false);
            writer.write(sBuilder.toString());
            //关闭流
            writer.close();
            br.close();

        } catch (Exception e) {
            String str = e.getMessage();
            System.out.println(str);
        }
    }
    
}

 

posted @ 2015-04-06 00:14  森林森  阅读(512)  评论(0编辑  收藏  举报