DOM解析XML

最近在搞XML,发现XML解析部分不记得多少了, 所以网上找了一些资料来补充下电。

demo包括3个calss:

Student : 是一个JavaBean ;

XmlManager:  XML 处理的class

XMlDemo:   demo  入口


xml文件内容格式:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
  <student>
    <name>y3wegy1</name>
    <age>23</age>
    <sex>male</sex>
  </student>
  <student>
    <name>y3wegy2</name>
    <age>24</age>
    <sex>male</sex>
  </student>
</root>


XmlManager.java:

package com.demo.xmldemo;

import com.demo.xmldemo.bean.Student;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * User: a549238
 * Date: 3/14/13
 * Time: 9:48 AM
 * To change this template use File | Settings | File Templates.
 */
public class XmlManager {
    private final  String filepath;
    public XmlManager(String filepath)
    {
            this.filepath=filepath;
    }

    /**
     *         create  XML FIle
     * @param studentList
     */
    public void creatXMLFile(List<Student> studentList)
    {
        File file=new File(filepath);
        if(file.exists())      // del  file  if  exists
            file.delete();
        DocumentBuilder documentBuilder= getDocumentBuilder();
        Document document=documentBuilder.newDocument();
        Element root= document.createElement("root");
        document.appendChild(root);
        for(Student student:studentList)
        {
            Element element=document.createElement("student");
            Element nameElement=document.createElement("name");
            Text nameText=document.createTextNode(student.getName()) ;
            nameElement.appendChild(nameText);
            Element ageElement=document.createElement("age");
            Text ageText=document.createTextNode(String.valueOf(student.getAge()));
            ageElement.appendChild(ageText);
            Element sexElement=document.createElement("sex");
            Text sexText=document.createTextNode(student.getSex());
            sexElement.appendChild(sexText);
            element.appendChild(nameElement);
            element.appendChild(ageElement);
            element.appendChild(sexElement);
            root.appendChild(element);
        }
        saveFile(filepath,document);   // save File
    }

    /**
     *  transform  XML  to  JavaBean :Strudent
     * @return
     */
    public List<Student> getAllStudents()
    {
        DocumentBuilder documentBuilder= getDocumentBuilder();
        List<Student> studentList=new ArrayList<Student>();
        try {
            Document document=documentBuilder.parse(new File(filepath));
            Element element=document.getDocumentElement();
            NodeList nodeList=element.getElementsByTagName("student");
            Element tempelement=null;
            NodeList nameNode=null,ageNode=null,sexNode=null;
            for(int i=0;i<nodeList.getLength();i++)
            {
                tempelement=(Element)nodeList.item(i);
                Student student=new Student();
                nameNode=tempelement.getElementsByTagName("name");
                student.setName(nameNode.item(0).getTextContent());
                ageNode=tempelement.getElementsByTagName("age");
                student.setAge(Integer.parseInt(ageNode.item(0).getTextContent()));
                sexNode=tempelement.getElementsByTagName("sex");
                student.setSex(sexNode.item(0).getTextContent());
                studentList.add(student);
            }
        } catch (SAXException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return studentList;
    }

    /**
     *   get Stuent by name
     * @param name
     * @return
     */
    public Student getStudentByName(String name)
    {
        List<Student>  allStudents = getAllStudents();
        for(Student student:allStudents)
        {
            if(student.getName().equals(name))
                return student;
        }
        return null;
    }

    public  void delNodeByName(String name)
    {
        DocumentBuilder documentBuilder=getDocumentBuilder();
        try {
            Document document=documentBuilder.parse(new File(filepath));
            Element root=document.getDocumentElement();
            NodeList nodeList=root.getElementsByTagName("student");
            Element tempElement=null;
            NodeList namenode=null;
            Node node=null;
            for(int i=0;i<nodeList.getLength();i++)
            {
                tempElement=(Element)nodeList.item(i);
                namenode=tempElement.getElementsByTagName("name");
                node= namenode.item(0);
                if(node.getTextContent().equals(name))
                {
                    node.getParentNode().getParentNode().removeChild(node.getParentNode());
                }
            }
            saveFile(filepath,document);
        } catch (SAXException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
    /**
     *   getDocumentBuilder
     * @return
     */
    private  DocumentBuilder getDocumentBuilder()
    {
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder= null;
        try {
            documentBuilder = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return documentBuilder;
    }

    private  void saveFile(String savefilepath,Document document)
    {
        try {
            //保存文件
            FileOutputStream fileOutputStream=new FileOutputStream(savefilepath);
            OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream);
            DOMSource domSource=new DOMSource(document);
            StreamResult streamResult=new StreamResult(outputStreamWriter);   //结果输出流
            TransformerFactory transformerFactory=TransformerFactory.newInstance();
            Transformer transformer=transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //编码
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");   //设置首行缩进
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); //缩进2格
            transformer.transform(domSource,streamResult);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        catch (TransformerException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

}

Student.java:

package com.demo.xmldemo.bean;

/**
 * Created with IntelliJ IDEA.
 * User: a549238
 * Date: 3/14/13

 * Time: 9:58 AM
 * To change this template use File | Settings | File Templates.
 */
public class Student {
    private String name;
    private String sex;
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        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;
    }
}

XmlDemo.java:

package com.demo.xmldemo;

import com.demo.xmldemo.bean.Student;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: a549238
 * Date: 3/14/13
 * Time: 9:47 AM
 * To change this template use File | Settings | File Templates.
 */
public class XmlDemo {
    private  String filepath=null;
    public  XmlDemo()
    {
        this.filepath="C:\\ss.xml";
    }
    public static void main(String[] args)
    {
        XmlDemo xmlDemo=new XmlDemo();
        xmlDemo.init();
        xmlDemo.getStudentByName("y3wegy1");
        xmlDemo.delByName("y3wegy2");

    }
    private void init()
    {
        List<Student> studentList=new ArrayList<Student>();
        Student student1=new Student();
        student1.setName("y3wegy1");
        student1.setSex("male");
        student1.setAge(23);
        studentList.add(student1);
        Student student2=new Student();
        student2.setName("y3wegy2");
        student2.setSex("male");
        student2.setAge(24);
        studentList.add(student2);
        XmlManager xmlManager=new XmlManager(filepath);
        xmlManager.creatXMLFile(studentList);
    }

    public  void getStudentByName(String name)
    {
        XmlManager xmlManager=new XmlManager(filepath);
        Student student=xmlManager.getStudentByName(name);
        System.out.println(student.getName()+"--"+student.getSex()+"--"+student.getAge());
    }
    public  void delByName(String name)
    {
        XmlManager xmlManager=new XmlManager(filepath);
        xmlManager.delNodeByName(name);
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值