52.md 12.1 KB
Newer Older
W
wizardforcel 已提交
1
# Java JDOM2 – 阅读 XML 示例
W
wizardforcel 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

> 原文: [https://howtodoinjava.com/xml/jdom2-read-parse-xml-examples/](https://howtodoinjava.com/xml/jdom2-read-parse-xml-examples/)

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

将 XML 文档加载到内存中后,JDOM2 维护严格的父子类型关系。 父类型的 JDOM 实例(父)具有访问其内容的方法,子类型的 JDOM 实例(内容)具有访问其父对象的方法。

```java
Table of Contents

Project Structure
JDOM2 Maven Dependency
Create JDOM2 Document
Read and filter XML content
Read XML Content with XPath
Complete Example
Sourcecode Download
```

## 项目结构

请创建此文件夹结构以执行示例。 这是在 Eclipse 中创建的[简单 Maven 项目。](//howtodoinjava.com/maven/create-a-simple-java-project-using-maven/)

![JDOM2 XML Parser](img/ed0b32780669a3c5c383c47c1e14ed4b.png)

Project Structure



请注意,我已经使用了 [lambda 表达式](//howtodoinjava.com/java8/complete-lambda-expressions-tutorial-in-java/)[方法引用](//howtodoinjava.com/java8/lambda-method-references-example/),因此您需要配置为使用 JDK 1.8。

## JDOM2 Maven 依赖关系

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

```

要执行 XPath,您还需要 jaxen。

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

```

## 创建 JDOM2 文档

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

1.  #### 使用 DOM 解析器

    ```java
    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 解析器

    ```java
    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 解析器

    ```java
    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`文件。

```java
<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()`方法。

```java
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());
}

```

输出:

```java
Root Element :: employees
```

#### 读取属性值

W
wizardforcel 已提交
176
使用 Element.getAttributeValue()方法。
W
wizardforcel 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

```java
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"));
}

```

Output:

```java
Id : 101
Id : 102
```

#### 读取元素值

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

```java
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"));
}

```

Output:

```java
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](//howtodoinjava.com/xml/how-to-work-with-xpaths-in-java-with-examples/) 读取任何元素的值集,您需要编译`XPathExpression`并使用其`evaluate()`方法。

```java
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());
}

```

Output:

```java
Employee Ids :: 101
Employee Ids :: 102

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

## 完整的 JDOM2 Read XML 示例

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

```java
package com.howtodoinjava.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();
	}*/
}

```

Output:

```java
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
```

## 源代码下载

[Download Sourcecode](//howtodoinjava.com/wp-content/downloads/JDOM2Examples.zip)

学习愉快!

参考文献:

[JDOM 网站](http://www.jdom.org/)
[JDOM2 入门](https://github.com/hunterhacker/jdom/wiki/JDOM2-A-Primer)