在Java中,可以使用JAXB(Java Architecture for XML Binding)来解析XML并自动生成实体类对象。以下是一个简单的例子:
首先,需要创建一个XML文件,例如books.xml:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>Java Programming for Beginners</title>
<author>John Smith</author>
<price>29.99</price>
</book>
<book>
<title>Advanced Java Programming</title>
<author>Jane Doe</author>
<price>39.99</price>
</book>
</books>
然后,在Java代码中定义一个实体类Book:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Book {
private String title;
private String author;
private double price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
注意,在实体类上需要加上@XmlRootElement注解。
最后,在Java代码中使用JAXB解析XML文件并生成Book对象:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Main {
public static void main(String[] args) {
try {
File file = new File("books.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Books books = (Books) jaxbUnmarshaller.unmarshal(file);
for (Book book : books.getBooks()) {
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Price: $" + book.getPrice());
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
这里我们还需要定义一个包装类Books,来包含多个Book对象:
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "books")
public class Books {
private List<Book> books;
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
运行上述代码,会输出:
Title: Java Programming for Beginners
Author: John Smith
Price: $29.99
Title: Advanced Java Programming
Author: Jane Doe
Price: $39.99
@我爱学习