簡體   English   中英

JAXB讀取XML文檔

[英]JAXB Reading XML document

我正在嘗試讀取XML文檔並將其解碼為Java Bean。 我的閱讀部分已經解決,但遇到一個問題。 我基本上是在嘗試解碼XML文檔的所有子節點,其根是“目錄”。 如何使用XMLDecoder做到這一點?

XMLDecoder:

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: unexpected element (uri:"", local:"catalog"). Expected elements are <{}book> jjavax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"catalog"). Expected elements are <{}book>

如何僅使用JAXB訪問子節點?

更新

目錄類別:

@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;
    }
}

正如JB Nizet所指出的,您肯定需要一個封閉的Catalog對象。 以下是能夠使用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. Catalog不需要@XmlAccessorType -Annotation,因為只有一個字段由@XmlElement注釋。
  2. 在將FIELD選擇為訪問類型時,將考慮所有字段,無論其可見性如何,除非使用@XmlTransient注釋。
  3. 書籍ID是文檔中的一個屬性,因此必須使用@XmlAttribute進行聲明。
  4. 必須使用Catalog.books上的@XmlElement來反映這本書元素的名稱。 JAXB默認為這將是一書代替,因此不匹配的元素的字段(或屬性)名稱。

如前所述,演示代碼是最低要求,應進行更改以滿足您的需要(即字段可見性,適當的構造函數,getter,equals,hashCode,toString等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM