Java读取、创建xml(通过dom方式)

转载 2016年07月05日 10:14:27

Java读取、创建xml(通过dom方式)

创建一个接口

XmlInterface.java

public interface XmlInterface {
 
        /**
        * 建立XML文档
        * @param fileName 文件全路径名称
        */
        public void createXml(String fileName);
        /**
        * 解析XML文档
        * @param fileName 文件全路径名称
        */
        public void parserXml(String fileName);
}

接口实现

XmlImpl.java

package com.test.xml;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
public class XmlImpl implements XmlInterface{
    private Document document;
 
    public void init() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            this.document = builder.newDocument();
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        }
    }
 
    public void createXml(String fileName) {
        Element root = this.document.createElement("scores");
        this.document.appendChild(root);
        Element employee = this.document.createElement("employee");
        Element name = this.document.createElement("name");
        name.appendChild(this.document.createTextNode("wangchenyang"));
        employee.appendChild(name);
        Element sex = this.document.createElement("sex");
        sex.appendChild(this.document.createTextNode("m"));
        employee.appendChild(sex);
        Element age = this.document.createElement("age");
        age.appendChild(this.document.createTextNode("26"));
        employee.appendChild(age);
        root.appendChild(employee);
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
            StreamResult result = new StreamResult(pw);
            transformer.transform(source, result);
            System.out.println("生成XML文件成功!");
        } catch (TransformerConfigurationException e) {
            System.out.println(e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (TransformerException e) {
            System.out.println(e.getMessage());
        }
    }
 
    public void parserXml(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(fileName);
             
            NodeList employees = document.getChildNodes();
            for (int i = 0; i < employees.getLength(); i++) {
                Node employee = employees.item(i);
                NodeList employeeInfo = employee.getChildNodes();
                for (int j = 0; j < employeeInfo.getLength(); j++) {
                    Node node = employeeInfo.item(j);
                    NodeList employeeMeta = node.getChildNodes();
                    for (int k = 0; k < employeeMeta.getLength(); k++) {
                        System.out.println(employeeMeta.item(k).getNodeName()
                                + ":" + employeeMeta.item(k).getTextContent());
                    }
                }
            }
            System.out.println("解析完毕");
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        } catch (SAXException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

测试

public class Main {
 
    public static void main(String args[]){
        XmlImpl dd=new XmlImpl();
        String str="D:/grade.xml";
        dd.init();
        dd.createXml(str);    //创建xml
        dd.parserXml(str);    //读取xml
    }
}

结果

生成xml

复制代码
<?xml version="1.0" encoding="GB2312"?>
<scores>
<employee>
<name>wangchenyang</name>
<sex>m</sex>
<age>26</age>
</employee>
</scores>
复制代码

读取xml

生成XML文件成功!
#text:
 
name:wangchenyang
#text:
 
sex:m
#text:
 
age:26
#text:
 
解析完毕


 

 

 

 

分类: J2SE, XML相关
标签: Java, 读取, xml, 创建
1
0
(请您对文章做出评价)
« 上一篇:Hibernate学习之一对一关联
» 下一篇:很长空格的String转换成Array数组

posted on 2011-08-23 14:34 重阳真人 阅读(31235) 评论(0) 编辑 收藏

</div>
<script type="text/javascript">var allowComments=true,isLogined=false,cb_blogId=95057,cb_entryId=2150530,cb_blogApp=currentBlogApp,cb_blogUserGuid='d6d4cfc4-3dc7-e011-8ee0-842b2b196315',cb_entryCreatedDate='2011/8/23 14:34:00';loadViewCount(cb_entryId);</script>

</div>

相关文章推荐

Java读取、创建xml(通过dom方式)

Java读取、创建xml(通过dom方式) 创建一个接口 XmlInterface.java ? public interface...

java--通过DOM方式对xml文件进行读取的简单实例

代码如下: package TestDemo; import javax.naming.NameNotFoundException; import javax.xml.parsers.Docume...

Java创建以及读写xml文档(dom方式)

package myXML; import org.w3c.dom.*; import org.xml.sax.*; import java.io.*; import javax.xml.par...

JAVA创建XML文件(三)---DOM4J方式创建XML

java中DOM4J方式创建XML

JAVA创建XML文件(一)---DOM方式创建XML

JAVA中以DOM方式创建XML文件

java29.XML操作------使用java DOM方式创建XML数据

示例代码:import java.io.File; import java.io.StringWriter;import javax.xml.parsers.DocumentBuilder; impo...

Java中DOM4J及JDOM 方式解析xml

books.xml: 冰与火之歌 乔治马丁 2014 89 安徒生童话 2004 77 English Book.java publi...

JAVA解析XML文件(四)---DOM4J方式解析

(1)导入DOM4J的JAR包 (2)xml文件内容 冰与火之歌 乔治·马丁 2015 200...

Java之DOM4J方式解析XML文件(学习笔记)

使用DOM4J方式解析XML文件,不是java官方提供的方法,所以我们的需要自己导入一个dom4j-1.6.1.jar包,下载地址为:http://download.csdn.net/detail/x...

Java之DOM4J方式生成XML文件(学习笔记)

使用DOM4J方式生成XML文件,不是java官方提供的方法,所以我们的需要自己导入一个dom4j-1.6.1.jar包,我们可以去官网下载。         样例代码: package com....
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Java读取、创建xml(通过dom方式)
举报原因:
原因补充:

(最多只允许输入30个字)