簡體   English   中英

JAXB:如何將元素與名稱空間綁定

[英]JAXB: How to bind element with namespace

他是我的XML托管在遠程計算機上:

<?xml version="1.0" encoding="UTF-8"?>
<store xmlns="http://mydomain.com/store/schemas">
    <!-- My Book store-->
    <book location="vk 1">
        <title>Learning JAXB</title>
        <author>Joe Blogg</author>
    </book>
    <book location="vk 1">
        <title>Learning JAXB SE</title>
        <author>Joe Blogg</author>
    </book>
</store>

我的裝訂書如下:

書籍裝訂:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "title", "author"})
public class Book
{
 private String title;
 private String author;
 private String location;

 @XmlElement(name = "title")
 public String getTitle()
 {
  return title;
 }

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

 @XmlAttribute(name = "location")
 public String getLocation()
 {
  return location;
 }

 public void setLocation(String location)
 {
  this.location = location;
 }

 @XmlElement(name = "author")
 public String getAuthor()
 {
  return author;
 }

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

商店綁定:

@XmlRootElement(name = "store", namespace = "http://mydomain.com/store/schemas")
public class Store
{
 private List<Book> books;

  @XmlElement(name="book")
  public List<Book> getBooks()
  {
    return books;
  }

  public void setBooks(List<Book> books)
  {
    this.books= books;
  }
}

我將按照以下說明解組XML文件:

  JAXBContext context = JAXBContext.newInstance(Store.class);
  Unmarshaller unmarshaller = context.createUnmarshaller();
  URL url = new URL("http://mydomain/files/store.xml");
  Store s= (Store) unmarshaller.unmarshal(url);
  System.out.println(s.getBooks());// Prints null

當我調用getBooks()我們得到空值。 有人可以在這里發現我在做什么錯嗎?

skaffman提供答案不正確。 您可以通過@XmlSchema在包級別指定名稱空間,或者使用@XmlType在類級別指定名稱空間,並將其用於限定字段/屬性:

欲獲得更多信息

我不確定100%,但是我認為可以通過在包級別(package-info.java)使用@XmlSchema批注來省略此重復項。

暫無
暫無

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

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