DOM模型的XML文件生成读取

import  org.w3c.dom.Document;
import  org.w3c.dom.Element;
import  org.w3c.dom.Text;
import  org.w3c.dom.Node;
import  org.w3c.dom.NodeList;
import  org.w3c.dom.NamedNodeMap;
import  org.w3c.dom.Attr;

import  javax.xml.parsers.DocumentBuilderFactory;
import  javax.xml.parsers.DocumentBuilder;

import  javax.xml.transform.Transformer;
import  javax.xml.transform.TransformerFactory;
import  javax.xml.transform.OutputKeys;

import  javax.xml.transform.dom.DOMSource;
import  javax.xml.transform.stream.StreamResult;

import  java.util.Properties;
import  java.io.FileOutputStream;
import  java.io.File;


public  class  WriteRead  {
    
public WriteRead() {
    }


    String FILE_NAME 
= "my.xml";

    
public void CreateXMLFile() throws Exception {
        
//生成Document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder dbr 
= dbf.newDocumentBuilder();
        Document doc 
= dbr.newDocument();

        
//添加内容
        
//根节点:
        Element root = doc.createElement("Root");
        root.setAttribute(
"att1""Hello");
        root.setAttribute(
"att2""World");

        Text rootText 
= doc.createTextNode("RootDate");

        root.appendChild(rootText);

        doc.appendChild(root);

        
//子节点:
        Element child = doc.createElement("Child");
        child.setAttribute(
"att1""Hello");
        child.setAttribute(
"att2""Earth");

        Text childText 
= doc.createTextNode("ChildDate");

        child.appendChild(childText);

        root.appendChild(child);

        
//孙子节点:
        Element grandchild = doc.createElement("GrandChild");
        grandchild.setAttribute(
"att1""Hello");
        grandchild.setAttribute(
"att2""Lover");

        Text grandchildText 
= doc.createTextNode("GrandChildDate");

        grandchild.appendChild(grandchildText);

        child.appendChild(grandchild);

        
//生成文件
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tfr 
= tff.newTransformer();
        Properties pts 
= tfr.getOutputProperties();
        pts.setProperty(OutputKeys.ENCODING, 
"GBK");
        tfr.setOutputProperties(pts);
        tfr.transform(
new DOMSource(doc),
                      
new StreamResult(new FileOutputStream(FILE_NAME, false)));
    }


    
public void ReadXMLFile() throws Exception {
        
//读取XML文件
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder dbr 
= dbf.newDocumentBuilder();
        File file 
= new File(FILE_NAME);
        Document doc 
= dbr.parse(file);

        Element root 
= doc.getDocumentElement();

        
//顺序读取所有节点及属性
        System.out.println("The root element is:" + root.getNodeName());

        NodeList children 
= root.getChildNodes();
        System.out.println(
"There are " + children.getLength() +
                           
" nodes in this document.");
        
        System.out.println(
"**********");
        
for (Node child = root.getFirstChild(); child != null;
                          child 
= child.getNextSibling()) {
            System.out.println(child.getNodeName() 
+ " = " +
                               child.getNodeValue());
        }


        System.out.println(
"**********");
        StepThrough(root);
        
        System.out.println(
"**********");
        StepThroughAll(root);

        
//读取指定节点的值
        System.out.println("**********");        
        NodeList nl 
= root.getElementsByTagName("GrandChild");        
        System.out.println(nl.item(
0).getFirstChild().getNodeValue());

        
//读取指定节点的属性值
        System.out.println("**********");
        NodeList n2 
= root.getElementsByTagName("Child");
        Element el2 
= (Element)n2.item(0);
        Attr attr 
= el2.getAttributeNode("att2");        
        System.out.println(attr.getValue());
    }

    
    
private void StepThrough(Node start) {
        System.out.println(start.getNodeName() 
+ " = " + start.getNodeValue());
        
for (Node child = start.getFirstChild(); child != null;
                          child 
= child.getNextSibling()) {
            StepThrough(child);
        }

    }


    
private void StepThroughAll(Node start) {
        System.out.println(start.getNodeName() 
+ " = " + start.getNodeValue());
        
if (start.getNodeType() == Node.ELEMENT_NODE) {
            NamedNodeMap startAtt 
= start.getAttributes();
            
for (int i = 0, len = startAtt.getLength(); i < len; i++{
                Node attr 
= startAtt.item(i);
                System.out.println(
" Attribute: " + attr.getNodeName() + " = " +
                                   attr.getNodeValue());
            }

        }

        
for (Node child = start.getFirstChild(); child != null;
                          child 
= child.getNextSibling()) {
            StepThroughAll(child);
        }

    }



    
public static void main(String[] args) {
        WriteRead writeread 
= new WriteRead();

        
try {
            writeread.CreateXMLFile();
        }
 catch (Exception e) {
            e.printStackTrace();
        }

        
try {
            writeread.ReadXMLFile();
        }
 catch (Exception e) {
            e.printStackTrace();
        }


    }

}
 
运行结果:
生成文件:
<? xml version="1.0" encoding="GBK" ?> < Root  att1 ="Hello"  att2 ="World" > RootDate < Child  att1 ="Hello"  att2 ="Earth" > ChildDate < GrandChild  att1 ="Hello"  att2 ="Lover" > GrandChildDate </ GrandChild ></ Child ></ Root >

打印结果:
The root element is:Root
There are 2 nodes in this document.
**********
#text = RootDate
Child = null
**********
Root = null
#text = RootDate
Child = null
#text = ChildDate
GrandChild = null
#text = GrandChildDate
**********
Root = null
 Attribute: att1 = Hello
 Attribute: att2 = World
#text = RootDate
Child = null
 Attribute: att1 = Hello
 Attribute: att2 = Earth
#text = ChildDate
GrandChild = null
 Attribute: att1 = Hello
 Attribute: att2 = Lover
#text = GrandChildDate
**********
GrandChildDate
**********
Earth
DOM模型:
org.w3c.dom
      • interface org.w3c.dom.Comment
      • interface org.w3c.dom.Text
读取,生成XML文件,用到javax.xml的一些东西。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值