首页 > 技术文章 > DOM操作XML实例

hzzhero 2015-06-30 23:00 原文

DTD如下:

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT 书籍列表 (计算机书籍)* >
<!ELEMENT 计算机书籍 ((书名,价格)+,作者+,简介,tel,hr)>
<!ELEMENT 书名     (#PCDATA)>
<!ELEMENT 价格    (#PCDATA)>
<!ELEMENT 作者    (#PCDATA)>
<!ELEMENT 简介     (#PCDATA)>
<!ELEMENT tel      (#PCDATA)>
<!ELEMENT hr    EMPTY>
<!ATTLIST 作者
    sex    CDATA    #IMPLIED
    age    CDATA    #IMPLIED
    phone    CDATA    #REQUIRED
    job        CDATA    #FIXED    "Writer"
    hobby    CDATA    "talking">

XML如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<书籍列表>
    <计算机书籍>
        <书名>thinking in java</书名>
        <价格>60</价格>
        <书名>thinking in XX</书名>
        <价格>80</价格>
        <作者 hobby="talking" job="Writer" phone="1212">gdfd</作者>
        <简介>java 圣经</简介>
        <tel>13661955777</tel>
        <hr/>
    </计算机书籍>
    <计算机书籍>
        <书名>thinking in C++</书名>
        <价格>100</价格>
        <作者 age="15" hobby="talking" job="Writer" phone="1213">qq</作者>
        <简介>C++ 圣经</简介>
        <tel>13661955732</tel>
        <hr/>
    </计算机书籍>
    <计算机书籍>
        <书名>I Love C++</书名>
        <价格>99</价格>
        <作者 age="44" hobby="talking" job="Writer" phone="139677">hzz</作者>
        </计算机书籍>
    </书籍列表>

程序如下:

package com.xml;
import javax.xml.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;

import com.sun.org.apache.xalan.internal.xsltc.cmdline.Transform;

public class DomXml {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse("webroot/NewFile.xml");
        //System.out.print(document);
        read(document);
        delete(document);
    }
    
    //删除书名为I LOVE C++的书
    public static void delete(Document doc) throws Exception{
        NodeList nl = doc.getElementsByTagName("书名");
        Node n=null;
        Node p=null;
        for(int i=0;i<nl.getLength();i++){
            if((n=nl.item(i)).getTextContent().equals("I Love C++")){
                (p=n.getParentNode()).getParentNode().removeChild(p);
                break;
            }
        }
        TransformerFactory tff = TransformerFactory.newInstance();
        //通过   得到一个转换器
        Transformer tf = tff.newTransformer();
        tf.transform(new DOMSource(doc), new StreamResult("webroot/NewFile.xml"));
    }
    
    public static void add(Document doc) throws Exception{
        Element newBook = doc.createElement("计算机书籍");
        Element newBook_name = doc.createElement("书名");
        Element newBook_price = doc.createElement("价格");
        Element newBook_auth = doc.createElement("作者");
        newBook_name.setTextContent("I Love C++");
        newBook_price.setTextContent("99");
        newBook_auth.setTextContent("hzz");
        newBook_auth.setAttribute("phone", "139677");
        newBook_auth.setAttribute("age", "44");
        newBook.appendChild(newBook_name);
        newBook.appendChild(newBook_price);
        newBook.appendChild(newBook_auth);
        
        //把新的书籍加到书籍列表
        doc.getDocumentElement().appendChild(newBook);
        //得到TransformerFactory
        TransformerFactory tff = TransformerFactory.newInstance();
        //通过   得到一个转换器
        Transformer tf = tff.newTransformer();
        tf.transform(new DOMSource(doc), new StreamResult("webroot/NewFile.xml"));
    }
    
    public static void read(Document document){
        NodeList nl = document.getElementsByTagName("计算机书籍");
        Element e =  (Element) nl.item(0);
        Element e2 = (Element) e.getElementsByTagName("作者").item(0);
        System.out.print(e2.getTextContent()+e2.getAttribute("phone"));
    }
    
    public static void list(Node node){
        if(node.getNodeType()==node.ELEMENT_NODE)
        System.out.println(node.getNodeName());
        else
        System.out.println(node.getTextContent()+node.getAttributes());
        NodeList nl = node.getChildNodes();
        for(int i=0;i<nl.getLength();i++){
            Node n = nl.item(i);
            list(n);
        }
    }

}

 

推荐阅读