Java JDOM2 - 读取 XML 示例

位置:首页>文章>详情   分类: Java教程 > 编程技术   阅读(246)   2023-06-26 07:54:18

JDOM 解析器 可用于读取 XML、解析 xml 以及在更新 XML 文件内容后写入 XML 文件。它将JDOM2 文档 存储在内存中以读取和修改它的值。

将 XML 文档加载到内存后,JDOM2 保持严格的父子类型关系。父类 JDOM 实例(Parent)具有访问其内容的方法,而子类 JDOM 实例(Content)具有访问其父类的方法。

项目结构

请创建此文件夹结构以执行示例。它是一个在eclipse 中创建的简单maven 项目

JDOM2 XML Parser

请注意,我使用了lambda 表达式方法引用,因此您需要配置项目以使用 JDK 1.8。

JDOM2 Maven 依赖

<dependency>
	<groupId>org.jdom</groupId>
	<artifactId>jdom2</artifactId>
	<version>2.0.6</version>
</dependency>

要执行 XPath,您还需要 jaxen。

<dependency>
	<groupId>jaxen</groupId>
	<artifactId>jaxen</artifactId>
	<version>1.1.6</version>
</dependency>

创建 JDOM2 文档

您可以使用下面列出的任何解析器创建 org.jdom2.Document 实例。它们都解析 XML 并返回内存中的 JDOM 文档

  1. 使用 DOM 解析器

    private static Document getDOMParsedDocument(final String fileName) 
    {
    	Document document = null;
    	try 
    	{
    		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    		//If want to make namespace aware.
            //factory.setNamespaceAware(true);
    		DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    		org.w3c.dom.Document w3cDocument = documentBuilder.parse(fileName);
    		document = new DOMBuilder().build(w3cDocument);
    	} 
    	catch (IOException | SAXException | ParserConfigurationException e) 
    	{
    		e.printStackTrace();
    	}
    	return document;
    }
  2. 使用 SAX 解析器

    private static Document getSAXParsedDocument(final String fileName) 
    {
    	SAXBuilder builder = new SAXBuilder(); 
    	Document document = null;
    	try 
    	{
    		document = builder.build(fileName);
    	} 
    	catch (JDOMException | IOException e) 
    	{
    		e.printStackTrace();
    	}
    	return document;
    }
  3. 使用 StAX 解析器

    private static Document getStAXParsedDocument(final String fileName) 
    {
    	
    	Document document = null;
    	try 
    	{
    		XMLInputFactory factory = XMLInputFactory.newFactory();
    		XMLEventReader reader = factory.createXMLEventReader(new FileReader(fileName));
    		StAXEventBuilder builder = new StAXEventBuilder(); 
    		document = builder.build(reader);
    	} 
    	catch (JDOMException | IOException | XMLStreamException e) 
    	{
    		e.printStackTrace();
    	}
    	return document;
    }

读取和过滤 XML 内容

我将阅读 employees.xml 文件。

<employees>
	<employee id="101">
		<firstName>Lokesh</firstName>
		<lastName>Gupta</lastName>
		<country>India</country>
		<department id="25">
			<name>ITS</name>
		</department>
	</employee>
	<employee id="102">
		<firstName>Brian</firstName>
		<lastName>Schultz</lastName>
		<country>USA</country>
		<department id="26">
			<name>DEV</name>
		</department>
	</employee>
</employees>

读取根节点

使用 document.getRootElement() 方法。

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

	Element rootNode = document.getRootElement();
	System.out.println("Root Element :: " + rootNode.getName());
}

输出:

Root Element :: employees

读取属性值

使用 Element.getAttributeValue() 方法。

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

	Element rootNode = document.getRootElement();

	rootNode.getChildren("employee").forEach( ReadXMLDemo::readEmployeeNode );
}

private static void readEmployeeNode(Element employeeNode) 
{
	//Employee Id
	System.out.println("Id : " + employeeNode.getAttributeValue("id"));
}

输出:

Id : 101
Id : 102

读取元素值

使用 Element.getChildText()Element.getText() 方法。

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

	Element rootNode = document.getRootElement();

	rootNode.getChildren("employee").forEach( ReadXMLDemo::readEmployeeNode );
}

private static void readEmployeeNode(Element employeeNode) 
{
	//Employee Id
	System.out.println("Id : " + employeeNode.getAttributeValue("id"));
	
	//First Name
	System.out.println("FirstName : " + employeeNode.getChildText("firstName"));
	
	//Last Name
	System.out.println("LastName : " + employeeNode.getChildText("lastName"));
	
	//Country
	System.out.println("country : " + employeeNode.getChild("country").getText());
	
	/**Read Department Content*/
	employeeNode.getChildren("department").forEach( ReadXMLDemo::readDepartmentNode );
}

private static void readDepartmentNode(Element deptNode) 
{
	//Department Id
	System.out.println("Department Id : " + deptNode.getAttributeValue("id"));
	
	//Department Name
	System.out.println("Department Name : " + deptNode.getChildText("name"));
}

输出:

FirstName : Lokesh
LastName : Gupta
country : India
Department Id : 25
Department Name : ITS

FirstName : Brian
LastName : Schultz
country : USA
Department Id : 26
Department Name : DEV

使用 XPath 读取 XML 内容

要使用 xpath 读取任何一组元素的值,您需要编译 XPathExpression 并使用它的 evaluate() 方法。

String xmlFile = "employees.xml";
Document document = getSAXParsedDocument(xmlFile);

XPathFactory xpfac = XPathFactory.instance();

//Read employee ids
XPathExpression<Attribute> xPathA = xpfac.compile("//employees/employee/@id", Filters.attribute());

for (Attribute att : xPathA.evaluate(document)) 
{
	System.out.println("Employee Ids :: " + att.getValue());
}

//Read employee first names
XPathExpression<Element> xPathN = xpfac.compile("//employees/employee/firstName", Filters.element());

for (Element element : xPathN.evaluate(document)) 
{
	System.out.println("Employee First Name :: " + element.getValue());
}

输出:

Employee Ids :: 101
Employee Ids :: 102

Employee First Name :: Lokesh
Employee First Name :: Brian

完整的 JDOM2 读取 XML 示例

这是在java中使用JDOM2读取xml的完整代码。

package com.cundage.demo.jdom2;

import java.io.FileReader;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.input.DOMBuilder;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.StAXEventBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.xml.sax.SAXException;

@SuppressWarnings("unused")
public class ReadXMLDemo 
{	
	public static void main(String[] args) 
	{
		String xmlFile = "employees.xml";
		Document document = getSAXParsedDocument(xmlFile);
		
		/**Read Document Content*/
		
		Element rootNode = document.getRootElement();
		System.out.println("Root Element :: " + rootNode.getName());
		
		System.out.println("\n=================================\n");
		
		/**Read Employee Content*/
		
		rootNode.getChildren("employee").forEach( ReadXMLDemo::readEmployeeNode );
		
		System.out.println("\n=================================\n");
		
		readByXPath(document);
	}
	
	private static void readEmployeeNode(Element employeeNode) 
	{
		//Employee Id
		System.out.println("Id : " + employeeNode.getAttributeValue("id"));
		
		//First Name
		System.out.println("FirstName : " + employeeNode.getChildText("firstName"));
		
		//Last Name
		System.out.println("LastName : " + employeeNode.getChildText("lastName"));
		
		//Country
		System.out.println("country : " + employeeNode.getChild("country").getText());
		
		/**Read Department Content*/
		employeeNode.getChildren("department").forEach( ReadXMLDemo::readDepartmentNode );
	}
	
	private static void readDepartmentNode(Element deptNode) 
	{
		//Department Id
		System.out.println("Department Id : " + deptNode.getAttributeValue("id"));
		
		//Department Name
		System.out.println("Department Name : " + deptNode.getChildText("name"));
	}
	
	private static void readByXPath(Document document) 
	{
		//Read employee ids
		XPathFactory xpfac = XPathFactory.instance();
		XPathExpression<Attribute> xPathA = xpfac.compile("//employees/employee/@id", Filters.attribute());
		for (Attribute att : xPathA.evaluate(document)) 
		{
			System.out.println("Employee Ids :: " + att.getValue());
		}
		
		XPathExpression<Element> xPathN = xpfac.compile("//employees/employee/firstName", Filters.element());
		for (Element element : xPathN.evaluate(document)) 
		{
			System.out.println("Employee First Name :: " + element.getValue());
		}
	}
	
	private static Document getSAXParsedDocument(final String fileName) 
	{
		SAXBuilder builder = new SAXBuilder(); 
		Document document = null;
		try 
		{
			document = builder.build(fileName);
		} 
		catch (JDOMException | IOException e) 
		{
			e.printStackTrace();
		}
		return document;
	}
	
	private static Document getStAXParsedDocument(final String fileName) 
	{
		
		Document document = null;
		try 
		{
			XMLInputFactory factory = XMLInputFactory.newFactory();
			XMLEventReader reader = factory.createXMLEventReader(new FileReader(fileName));
			StAXEventBuilder builder = new StAXEventBuilder(); 
			document = builder.build(reader);
		} 
		catch (JDOMException | IOException | XMLStreamException e) 
		{
			e.printStackTrace();
		}
		return document;
	}
	
	private static Document getDOMParsedDocument(final String fileName) 
	{
		Document document = null;
		try 
		{
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			//If want to make namespace aware.
	        //factory.setNamespaceAware(true);
			DocumentBuilder documentBuilder = factory.newDocumentBuilder();
			org.w3c.dom.Document w3cDocument = documentBuilder.parse(fileName);
			document = new DOMBuilder().build(w3cDocument);
		} 
		catch (IOException | SAXException | ParserConfigurationException e) 
		{
			e.printStackTrace();
		}
		return document;
	}
	
	/*private static String readFileContent(String filePath) 
	{
	    StringBuilder contentBuilder = new StringBuilder();
	    try (Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8)) 
	    {
	        stream.forEach(s -> contentBuilder.append(s).append("\n"));
	    }
	    catch (IOException e) 
	    {
	        e.printStackTrace();
	    }
	    return contentBuilder.toString();
	}*/
}

输出:

Root Element :: employees

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

Id : 101
FirstName : Lokesh
LastName : Gupta
country : India
Department Id : 25
Department Name : ITS
Id : 102
FirstName : Brian
LastName : Schultz
country : USA
Department Id : 26
Department Name : DEV

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

Employee Ids :: 101
Employee Ids :: 102
Employee First Name :: Lokesh
Employee First Name :: Brian

快乐学习!!

参考:

JDOM 网站
JDOM2 入门

标签2: Java XML JDOM2 XML Files
地址:https://www.cundage.com/article/jdom2-read-parse-xml-examples.html

相关阅读

JDOM 解析器 可用于读取 XML、解析 xml 以及在更新 XML 文件内容后写入 XML 文件。它将JDOM2 文档 存储在内存中以读取和修改它的值。 将 XML 文档加载到内存后,JDO...
很多时候我们需要解析一个 XML 文件并从中提取信息。例如,使用 xpath 读取 XML 元素的属性值。在此 Java XPath 教程中,学习从 XML 字符串获取属性值。 我正在使用 jd...
读取 XML 文件和打印 XML 字符串以控制或将 XML 写入文件的 Java 示例。 1) 将 XML 转换为字符串 转换 XML 对象即 org.w3c.dom.Document 成字符串...
在 Java 中,XML 用 org.w3c.dom.Document 对象表示。在本 XML 教程中,我们将学习 – 将 XML 字符串转换为 XML 文档 将 XML 文件内容转换为 XML...
在此Java xml 解析器教程中,学习在Java 中使用DOM 解析器读取xml。 DOM 解析器旨在将 XML 作为内存中的对象图(树状结构)进行处理——所谓的“文档对象模型 (DOM)”。...
将 Java 对象写入 XML 的 Java 示例。存储在 Java 对象字段中的信息可以写入 XML 文件 或简单地写入 XML 字符串。 1) 将 Java 对象转换为 XML 字符串 要将...
从 XML 文件创建 .properties 文件的 Java 示例。此代码可用于从 XML 文件中读取属性键值,以在应用程序代码中使用。 XML 示例的属性 要将 XML 文件转换为属性文件,...
学习使用 Java StAX 解析器解析和读取 XML 文件。 StAX(XML 流 API)提供了两种解析 XML 的方法,即基于游标的 API 和基于迭代器的 API。 1) StAX解析器...
学习根据架构 (xsd) 验证 XML,然后将 XML 解组为 Java 对象。如果验证失败,还要学习检查 xml 架构验证期间的验证错误。 更多参考:如何从 JAXB 类生成模式 1. XSD...
Java xpath 示例 读取 XML 文件并解析为 DOM 对象,然后评估 org.w3c.dom.Document 对象上的 xpath 并获得结果以 String 或 NodeList ...