import java.util.List;

public class Book {
    private String id;
    private String author;
    private String title;
    private String genre;
    private double price;
    private String publish_date;
    private String description;

    public Book(String id, String author, String title, String genre, double price, String publish_date, String description) {
        this.id = id;
        this.author = author;
        this.title = title;
        this.genre = genre;
        this.price = price;
        this.publish_date = publish_date;
        this.publish_date = publish_date;
        this.description = description;
    }

    public String getId() {
        return id;
    }

    public String getAuthor() {
        return author;
    }

    public String getTitle() {
        return title;
    }

    public String getGenre() {
        return genre;
    }

    public double getPrice() {
        return price;
    }

    public String getPublish_date() {
        return publish_date;
    }

    public String getDescription() {
        return description;
    }
}

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import java.util.ArrayList;

public class Catalog {
    private List<Book> books;

    public Catalog() {
        books = new ArrayList<>();
    }

    public void loadFromXML(String filePath) {
        try {
            File xmlFile = new File(filePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);

            doc.getDocumentElement().normalize();

            NodeList bookList = doc.getElementsByTagName('book');

            for (int i = 0; i < bookList.getLength(); i++) {
                Node bookNode = bookList.item(i);

                if (bookNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element bookElement = (Element) bookNode;

                    String id = bookElement.getAttribute('id');
                    String author = bookElement.getElementsByTagName('author').item(0).getTextContent();
                    String title = bookElement.getElementsByTagName('title').item(0).getTextContent();
                    String genre = bookElement.getElementsByTagName('genre').item(0).getTextContent();
                    double price = Double.parseDouble(bookElement.getElementsByTagName('price').item(0).getTextContent());
                    String publish_date = bookElement.getElementsByTagName('publish_date').item(0).getTextContent();
                    String description = bookElement.getElementsByTagName('description').item(0).getTextContent();

                    Book book = new Book(id, author, title, genre, price, publish_date, description);
                    books.add(book);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Book> getBooks() {
        return books;
    }
}

public class Main {
    public static void main(String[] args) {
        Catalog catalog = new Catalog();
        catalog.loadFromXML('path_to_xml_file.xml');

        List<Book> books = catalog.getBooks();

        for (Book book : books) {
            System.out.println('ID: ' + book.getId());
            System.out.println('Author: ' + book.getAuthor());
            System.out.println('Title: ' + book.getTitle());
            System.out.println('Genre: ' + book.getGenre());
            System.out.println('Price: ' + book.getPrice());
            System.out.println('Publish Date: ' + book.getPublish_date());
            System.out.println('Description: ' + book.getDescription());
            System.out.println('---------------------------------------');
        }
    }
}

步骤:

  1. 创建Book类: 创建一个名为Book的类来表示XML文件中的每个book元素。每个Book对象将包含id、author、title、genre、price、publish_date和description属性。
  2. 创建Catalog类: 创建一个名为Catalog的类来管理所有Book对象。Catalog类包含一个名为books的List,用于存储从XML文件解析出来的所有Book对象。Catalog类还包含一个loadFromXML方法,该方法用于解析XML文件并将数据映射到Book对象。
  3. 解析XML文件: 使用DocumentBuilderFactory和DocumentBuilder解析XML文件。使用getElementsByTagName方法获取所有book元素,并使用getAttribute和getTextContent方法获取每个元素的属性和值。
  4. 创建Book对象: 使用解析出来的数据创建Book对象,并将这些对象添加到Catalog类中的books列表中。
  5. 显示结果: 迭代books列表,并打印每个Book对象的属性。

注意:

  • 将'path_to_xml_file.xml'替换为实际的XML文件路径。
  • 确保您的项目中包含JAXP库。
  • 可以使用其他解析方法,例如SAX解析器,但这超出了本教程的范围。

其他优化:

  • 使用更清晰的变量名。
  • 使用错误处理来处理潜在的异常。
  • 使用日志记录来记录解析过程。
  • 使用更高级的XML解析库,例如JAXB,来简化解析过程。
Java XML解析:将XML文件转换为Java对象

原文地址: https://www.cveoy.top/t/topic/qg2r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录