首頁 > Java > java教程 > 主體

詳解Java利用dom方式讀取、建立xml的實例程式碼

黄舟
發布: 2017-03-16 10:28:56
原創
1683 人瀏覽過

這篇文章主要介紹了Java 利用dom方式讀取、創建xml的相關資料,需要的朋友可以參考下

Java 利用dom方式讀取、建立xml詳解

1.建立一個介面

#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:
 
解析完毕
登入後複製

以上是詳解Java利用dom方式讀取、建立xml的實例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!