当前位置: 首页 > 知识库问答 >
问题:

JAXB读取XML文档

白翰海
2023-03-14
private static Book jaxbXMLToObject() {
    try {
        JAXBContext context = JAXBContext.newInstance(Book.class);
        Unmarshaller un = context.createUnmarshaller();
        Book book = (Book) un.unmarshal(new File("PATH"));
        return book;
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;
}

我正在阅读下面的文件

    <?xml version="1.0"?>
    <catalog>
       <book id="1">
          <author>Isaac Asimov</author>
          <title>Foundation</title>
          <genre>Science Ficition</genre>
          <price>164</price>
          <publish_date>1951-08-21</publish_date>
          <description>Foundation is the first novel in Isaac Asimovs Foundation Trilogy (later expanded into The Foundation Series). Foundation is a cycle of five interrelated short stories, first published as a single book by Gnome Press in 1951. Collectively they tell the story of the Foundation, an institute to preserve the best of galactic civilization after the collapse of the Galactic Empire.</description>
       </book>
   </catalog>

并将其解析为Book对象

@XmlRootElement(name = "book")
@XmlType(propOrder = {"id", "price", "title", "author", "genre", "description"})
public class Book {
    private int id;
    private int price;
    private String title;
    private String author;
    private String genre;
    private String description;
    private Date publish_date;

    public Book() {

    }

……。我得到错误:jjavax.xml.bind.unmarshalException:意外元素(URI:“”,local:“catalog”)。需要的元素为<{}book>

@XmlRootElement(name = "catalog")

    public class Catalog {
        @XmlElement(name = "book")
        List<Book> books;

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

        public void setBooks(List<Book> books) {
            this.books = books;
        }
    }
@XmlAccessorType(XmlAccessType.FIELD)
public class Book {
    @XmlAttribute
    int id;
    private int price;
    private String title;
    private String author;
    private String genre;
    private String description;
    private Date publish_date;

    public Book() {

    }

    public Book(int id, int price, String title, String genre, String description, Date publicationDate) {
        this.id = id;
        this.price = price;
        this.title = title;
        this.genre = genre;
        this.description = description;
        this.publish_date = publicationDate;
    }

    public int getId() {
        return id;
    }

    public int getPrice() {
        return price;
    }

    public String getTitle() {
        return title;
    }

    public String getGenre() {
        return genre;
    }

    public String getDescription() {
        return description;
    }

    public Date getPublicationDate() {
        return publish_date;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setPublish_date(String publish_date) {
        this.publish_date = new Date();
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getPublish_date() {
        return publish_date;
    }

    public String toJSON() {
        ObjectMapper mapper = new ObjectMapper();

        try {
            return mapper.writeValueAsString(this);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", price=" + price +
                ", title='" + title + '\'' +
                ", genre='" + genre + '\'' +
                ", description='" + description + '\'' +
                ", publicationDate=" + publish_date +
                '}';
    }
}

道:

public class BooksDAO {

    public BooksDAO() {
    }

    public List<Book> getBooks() {
        Catalog catalog = jaxbXMLToObject();
        return catalog.getBooks();
    }

    private static Catalog jaxbXMLToObject() {
        try {
            return JAXB.unmarshal(new File("PATH"), Catalog.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

共有1个答案

杨和蔼
2023-03-14

正如JB Nizet已经指出的,您肯定需要一个附带的目录对象。以下是能够使用JAXB解封提供的XML文档并从中提取本书的最低限度:

public class ReadXMLUsingJAXB {

    static class Catalog {
        @XmlElement(name = "book")
        List<Book> books;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    static class Book {
        @XmlAttribute
        int id;
        String author;
        String title;
        String genre;
        int price;
        Date publish_date;
        String description;
    }

    private static Book firstBookFromXML() {
        Catalog catalog = JAXB.unmarshal(new File("PATH"), Catalog.class);
        return catalog.books.get(0);
    }

    public static void main(String[] args) {
        Book book = firstBookFromXML();
        System.out.println(book.id + ", " + book.author + ", " + book.title 
                + ", " + book.genre + ", " + book.price 
                + ", " + book.publish_date + ", " + book.description);
    }

}

这里有些事情值得一提:

  1. @xmlaccessortype-Catalog不需要注释,因为只有一个字段用@xmlelement注释。
  2. 在选择字段作为访问类型时,将考虑所有字段,无论其可见性如何,除非使用@xmltransiste进行注释。
  3. 图书ID是文档中的一个属性,因此必须使用@xmlattribute.
  4. 将其声明为属性 catalog.books上的
  5. @xmlelement是反映book-elements名称所必需的。JAXB默认为字段(或属性)名称,该名称将改为books,因此与元素不匹配。
 类似资料:
  • 问题内容: 我想读取一个xml文件(如下所示),但是我得到了执行权。您能帮我解决这个问题吗? 这是我想要读取xml文件的代码: } 最后,这是我得到的异常: Env POJO类别: POJO类别: 问题答案: 您需要确保使用或将类与XML文档的根元素相关联(请参阅:http : //blog.bdoughan.com/2012/07/jaxb-and-root- elements.html )。或

  • 问题内容: 我试图从XML文件中读取一些数据,但遇到麻烦,我拥有的XML如下: 我试图将这些值作为字符串读取到我的Java程序中,到目前为止,我已经编写了以下代码: 我正在努力读取实际的字符串值。 问题答案: 可能的实现之一: 与XML内容一起使用时: 结果并分配给上述和参考。

  • 我在从xml文件中读取信息时遇到了一点问题... 传给我的文件有几千行。我只对300-400行感兴趣。当用户完成操作并且要读取的数据可以存储在中时,我不需要将任何数据写回xml。 我只对最内部名称元素的感兴趣(前两个是“098-0031”和“098-0032”)。 这是我的代码: 但是条件从来没有填满...谁能给我解释一下为什么。也许可以向我展示一种简单的方法来将这些值存储在中?提前感谢! 编辑:

  • 我在这里看到了一个类似的问题,但它并没有帮助我解决这个问题,所以我在这里发布我的问题,看看是否有人可以修改我的代码使其工作。 问:如何访问混合内容字符串值并将其保存在 setPhrase(字符串值)方法中? 标题.xml: 标题.java: 在使用JAXB解组和编组之后,我能够将所有内容转换为和对象并保存为相应的内容,但实际短语“Hello World”除外。我知道我必须为这个复杂的元素使用某种@

  • 我的猜测是我没有以正确的方式声明模式文档,但我不知道错误到底在哪里。我做错了什么?

  • 导语 XML(ExtensibleMarkup Language,可扩展标记语言),是一种类似于HTML的标记语言,但它的设计目的是用来传输数据,而不是显示数据。XML的标签没有被预定义,用户需要在使用时自行进行定义。XML是W3C(万维网联盟)的推荐标准。相对于数据库表格的二维表示,XML使用的树形结构更能表现出数据的包含关系,作为一种文本文件格式,XML简单明了的特性使得它在信息存储和描述领域