`
y8820960
  • 浏览: 112986 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

DOM操作XML实例

    博客分类:
  • XML
阅读更多
student.xml:
<?xml version="1.0" encoding="UTF-8"?>
<students>
	<student>
		<name>Stone</name>
		<age>26</age>
		<sex>男</sex>
		<address>北京</address>
	</student>
	<student>
		<name>Snow</name>
		<age>24</age>
		<sex>女</sex>
		<address>北京</address>
	</student>
</students>

实体类student:
package com.xml;

public class Student
{
    String name;
    
    String sex;
    
    String age;
    
    public Student(String name, String sex, String age)
    {
        // TODO Auto-generated constructor stub
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    
    public String getName()
    {
        return name;
    }
    
    public void setName(String name)
    {
        this.name = name;
    }
    
    public String getSex()
    {
        return sex;
    }
    
    public void setSex(String sex)
    {
        this.sex = sex;
    }
    
    public String getAge()
    {
        return age;
    }
    
    public void setAge(String age)
    {
        this.age = age;
    }
    
}


package com.xml;

import java.io.File;
import java.io.IOException;

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.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMForXml
{
    /**
     * 获取document对象
     */
    public Document getDocument(String path)
    {
        Document doc = null;
        try
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(new File(path));
        }
        catch (ParserConfigurationException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (SAXException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return doc;
    }
    
    /**
     * 解析xml
     */
    public void parseXml(String path)
    {
        Document doc = this.getDocument(path);
        NodeList nodeList = doc.getElementsByTagName("student");
        for (int i = 0; i < nodeList.getLength(); i++)
        {
            StringBuffer str = new StringBuffer();
            str.append("姓名:"
                    + doc.getElementsByTagName("name")
                            .item(i)
                            .getFirstChild()
                            .getNodeValue());
            str.append(",");
            str.append("性别:"
                    + doc.getElementsByTagName("sex")
                            .item(i)
                            .getFirstChild()
                            .getNodeValue());
            str.append(",");
            str.append("年龄:"
                    + doc.getElementsByTagName("age")
                            .item(i)
                            .getFirstChild()
                            .getNodeValue());
            str.append(",");
            System.out.println(str.toString());
        }
    }
    /**
     * 保存到文件
     */
    public void modifyFile(Document doc,String distFileName) 
    {
        try
        {
            TransformerFactory tf = TransformerFactory.newInstance(); 
            Transformer transformer = tf.newTransformer();
            DOMSource domSource = new DOMSource(doc);
            StreamResult sr = new StreamResult(new File("src/student.xml"));
            transformer.transform(domSource,sr);
        }
        catch (TransformerConfigurationException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (TransformerException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * new 一个 student
     */
    public void addNode(Student student)
    {
        Document doc = this.getDocument("src/student.xml");
        NodeList nodeList = doc.getElementsByTagName("students");
        //1 创建新节点
        Node stuNode = doc.createElement("student");
        Node nameNode = doc.createElement("name");
        nameNode.appendChild(doc.createTextNode(student.getName()));
        Node sexNode = doc.createElement("sex");
        sexNode.appendChild(doc.createTextNode(student.getSex()));
        Node ageNode = doc.createElement("age");
        ageNode.appendChild(doc.createTextNode(student.getAge()));
        //2 添加
        stuNode.appendChild(nameNode);
        stuNode.appendChild(sexNode);
        stuNode.appendChild(ageNode);
        nodeList.item(0).appendChild(stuNode);
        //3 保存
        this.modifyFile(doc, "src/student.xml");
    }
    /**
     * 删除一个节点
     */
    public void deleteNode(String name)
    {
        Document doc = this.getDocument("src/student.xml");
        NodeList nodeList = doc.getElementsByTagName("name");
        for(int i=0; i<nodeList.getLength(); i++) 
        {
            String value = nodeList.item(i).getFirstChild().getTextContent();
            if(name != null && name.equalsIgnoreCase(value)) 
            {
                Node parentNode = nodeList.item(i).getParentNode();
                doc.getFirstChild().removeChild(parentNode);
            }
            modifyFile(doc,"src/student.xml");
        }
    }
    /**
     * 修改一个节点
     */
    public void updateNode(String name) 
    {
        Document doc = this.getDocument("src/student.xml");
        NodeList nodeList = doc.getElementsByTagName("name");
        for (int i=0; i<nodeList.getLength(); i++) 
        {
            String value = nodeList.item(i).getFirstChild().getTextContent();
            if(name != null && name.equalsIgnoreCase(value)) 
            {
                Node parentNode = nodeList.item(i).getParentNode();
                NodeList nl = parentNode.getChildNodes();
                for (int j=0; j<nl.getLength(); j++) 
                {
                    String modifyNode = nl.item(j).getNodeName();
                    if(modifyNode.equalsIgnoreCase("age")) 
                    {
                        nl.item(j).getFirstChild().setTextContent("100");
                    }
                }
            }
        }
        this.modifyFile(doc, "src/student.xml");
    }
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics