使用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(),这些都是要注意的,很容易由于惯性就写错了。我代码写的不是很好,若是有什么问题和建议欢迎你们给我提,就写到这吧。加油!文档

相关文章
相关标签/搜索