Java读取XML

Read an XML File using DOM Parser in Java

html 复制代码
<employees>
    <employee id="111">
        <firstName>Lokesh</firstName>
        <lastName>Gupta</lastName>
        <location>India</location>
    </employee>
    <employee id="222">
        <firstName>Alex</firstName>
        <lastName>Gussin</lastName>
        <location>Russia</location>
    </employee>
    <employee id="333">
        <firstName>David</firstName>
        <lastName>Feezor</lastName>
        <location>USA</location>
    </employee>
</employees>

* XmlDomParser.java

java 复制代码
package org.example;

import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

/* @ref:https://howtodoinjava.com/java/xml/read-xml-dom-parser-example/ */
public class XmlDomParser {
    public static Document readXMLDocumentFromFile(String fileNameWithPath)
            throws ParserConfigurationException, IOException, SAXException {
        //Get Document Builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        //Build Document
        Document document = builder.parse(new File(fileNameWithPath));
        //Normalize the XML Structure; It's just too important !!
        document.getDocumentElement().normalize();
        return document;
    }

    public static void main(String[] args) {
        try {
            Document document = readXMLDocumentFromFile("employees.xml");

            //Verify XML Content

            //Here comes the root node
            Element root = document.getDocumentElement();
            System.out.println(root.getNodeName());

            //Get all employees
            NodeList nList = document.getElementsByTagName("employee");
            System.out.println("============================");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node node = nList.item(temp);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    //Print each employee's detail
                    Element eElement = (Element) node;
                    System.out.println("\nEmployee id : " + eElement.getAttribute("id"));
                    System.out.println("First Name : " + eElement.getElementsByTagName("firstName").item(0).getTextContent());
                    System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
                    System.out.println("Location : " + eElement.getElementsByTagName("location").item(0).getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

C:\Users\admin\.jdks\corretto-1.8.0_352\bin\java.exe "-javaagent:E:\Program Files\JetBrains\IntelliJ IDEA 2022.2.3\lib\idea_rt.jar=60391:E:\Program Files\JetBrains\IntelliJ IDEA 2022.2.3\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\charsets.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\access-bridge-64.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\cldrdata.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\dnsns.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\jaccess.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\jfxrt.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\localedata.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\nashorn.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\sunec.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\sunjce_provider.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\sunmscapi.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\sunpkcs11.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\ext\zipfs.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\jce.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\jfr.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\jfxswt.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\jsse.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\management-agent.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\resources.jar;C:\Users\admin\.jdks\corretto-1.8.0_352\jre\lib\rt.jar;M:\Projects\XmlDomParse\target\classes org.example.XmlDomParser

============================

Employee id : 111

First Name : Lokesh

Last Name : Gupta

Location : India

Employee id : 222

First Name : Alex

Last Name : Gussin

Location : Russia

Employee id : 333

First Name : David

Last Name : Feezor

Location : USA

Process finished with exit code 0

jdk1.8自带的包,不需要maven引入第三方包。

相关推荐
Grey Zeng3 小时前
Java SE 25新增特性
java·jdk·jdk新特性·jdk25
雨白4 小时前
Java 线程通信基础:interrupt、wait 和 notifyAll 详解
android·java
excel4 小时前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着4 小时前
全栈框架next.js入手指南
前端·next.js
你的人类朋友6 小时前
什么是API签名?
前端·后端·安全
会豪8 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子8 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶8 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子8 小时前
深入剖析 useState产生的 setState的完整执行流程
前端
架构师沉默8 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构