books.xml:
<?xml version="1.0" encoding="utf-8" ?>
< books>
< book id = " 001" >
< title> Harry Potter</ title>
< author> J K. Rowling</ author>
< price> $50.2</ price>
</ book>
< book id = " 002" >
< title> Learning XML</ title>
< author> Erik T. Ray</ author>
< price> $90</ price>
</ book>
</ books>
引入jdom包的maven依赖:
< dependency>
< groupId> org.jdom</ groupId>
< artifactId> jdom</ artifactId>
< version> 2.0.0</ version>
</ dependency>
读取xml文件程序:
import org. jdom2. Document;
import org. jdom2. JDOMException;
import org. jdom2. input. SAXBuilder;
import java. io. File;
import java. io. IOException;
public class MyXmlReader {
static class Book {
String title;
String author;
String price;
public Book ( String title, String author, String price) {
this . title = title;
this . author = author;
this . price = price;
}
public void read ( ) {
System. out. println ( "title: " + title+ " author: " + author+ " price: " + price) ;
}
}
public static void main ( String[ ] args) {
try {
SAXBuilder builder = new SAXBuilder ( ) ;
Document document = builder. build ( new File ( "src/main/resources/books.xml" ) ) ;
document. getRootElement ( ) . getChildren ( ) . stream ( )
. map ( child- > {
return new Book ( child. getChildText ( "title" )
, child. getChildText ( "author" )
, child. getChildText ( "price" ) ) ;
} ) . forEach ( Book: : read) ;
} catch ( IOException | JDOMException e) {
e. printStackTrace ( ) ;
}
}
}
输出结果:
title: Harry Potter author: J K. Rowling price: $50.2
title: Learning XML author: Erik T. Ray price: $90