使用Java解析XML文件並在控制檯原樣輸出

這是我第一次寫博客,今天初次接觸XML文件的解析,感受有點繞,可是最後仍是本身作出來了,想一想仍是寫寫吧,記錄本身的成長曆程java

xml文件樣式:node

<?xml version="1.0" encoding="utf-8"?>
<students>
    <student id="001">   
        <name>張三</name>     
        <age>23</age>    
        
<address>USA</address>    
    </student>
    <student id="002">
        <name>李四</name>
        <age>24</age>
        <address>USA</address>
    </student>
    <student id="003">
        <name>王五</name>
        <age>25</age>
        <address>USA</address>
    </student>
</students>數組

Java代碼:dom

package com.gem.java.parsexml;ui

import java.io.IOException;spa

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;utf-8

public class CompleteParseXML {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=factory.newDocumentBuilder();
        Document document=builder.parse("src/hello.xml");
        
        Element students=document.getDocumentElement();
        System.out.print("<"+students.getNodeName()+">");
        NodeList stuNodeList=students.getChildNodes();
        for (int i = 0; i < stuNodeList.getLength(); i++) {
            Node stuNode=stuNodeList.item(i);
            printNode(stuNode);
        }
        System.out.print("</"+students.getNodeName()+">");
    }
    
    static void printNode(Node node){
        if(node.getNodeType()==Node.ELEMENT_NODE){
            System.out.print("<"+node.getNodeName());
            NamedNodeMap attr=node.getAttributes();
            for (int i = 0; i < attr.getLength(); i++) {
                Node attrNode=attr.item(i);
                System.out.print(" "+attrNode.getNodeName()+"=\""+attrNode.getNodeValue()+"\"");
            }
            System.out.print(">");
            NodeList childsNode=node.getChildNodes();
            for (int i = 0; i < childsNode.getLength(); i++) {
                Node childNode=childsNode.item(i);
                printNode(childNode);
            }
            System.out.print("</"+node.getNodeName()+">");
        }else {
            System.out.print(node.getNodeValue());
        }
        
    }
}
首先要獲取到文檔的根節點元素,節點有元素節點,屬性節點,文本節點。標籤 <student id="001"></student>下有七個子節點,這個很容易被弄錯,紅色標出的是4個文本節點,另外3個標籤是元素節點。我我的感受DOM操做的API有點不按套路出牌,好比獲取節點NodeList類型變量中獲取子節點用item(index),我直接用了get(index),發現不對,又用了數組的取值方式,也是不對,最後才弄出來,還有獲取其長度時使用getLength(),而不是length或者size(),這些都是要注意的,很容易由於慣性就寫錯了。我代碼寫的不是很好,若是有什麼問題和建議歡迎你們給我提,就寫到這吧。加油!文檔

相關文章
相關標籤/搜索