DOM模型的XML文件生成读取

来源:互联网 发布:变调软件手机版 编辑:程序博客网 时间:2024/05/12 06:35
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.DOMImplementation
  • interface org.w3c.dom.NamedNodeMap
  • interface org.w3c.dom.Node
    • interface org.w3c.dom.Attr
    • interface org.w3c.dom.CharacterData
      • interface org.w3c.dom.Comment
      • interface org.w3c.dom.Text
        • interface org.w3c.dom.CDATASection
    • interface org.w3c.dom.Document
    • interface org.w3c.dom.DocumentFragment
    • interface org.w3c.dom.DocumentType
    • interface org.w3c.dom.Element
    • interface org.w3c.dom.Entity
    • interface org.w3c.dom.EntityReference
    • interface org.w3c.dom.Notation
    • interface org.w3c.dom.ProcessingInstruction
  • interface org.w3c.dom.NodeList

读取,生成XML文件,用到javax.xml的一些东西。

原创粉丝点击