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引入第三方包。

相关推荐
在未来等你23 分钟前
互联网大厂Java求职面试:AI大模型融合下的企业知识库架构设计与性能优化
java·向量数据库·ai大模型·spring ai·语义缓存·rag系统·多模态处理
寻星探路30 分钟前
JAVA与C语言之间的差异(一)
java·开发语言
tqs_1234541 分钟前
IntelliJ IDEA 中进行背景设置
java·ide·intellij-idea
爱上语文1 小时前
MyBatisPlus(1):快速入门
java·开发语言·数据库·后端·mybatis
Mintopia1 小时前
计算机图形学的奇幻之旅:第三天探索
前端·javascript·计算机图形学
Mintopia1 小时前
Three.js 物理材质:打造 3D 世界的 “魔法皮肤”
前端·javascript·three.js
异常君1 小时前
Java 与 Go 语言协作开发实战指南
java·go
信徒_1 小时前
Cloudflare
java
知识分享小能手2 小时前
Typescript学习教程,从入门到精通,TypeScript 泛型与类型操作详解(二)(17)
前端·javascript·学习·typescript·jquery·前端网页学习
stark张宇2 小时前
Web - Javascript 函数与DOM、BOM
前端