JAXB:如何将元素与命名空间绑定

Bit*_*map 2 java xml jaxb

他是我在远程机器上托管的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>
Run Code Online (Sandbox Code Playgroud)

我有绑定书如下:

书籍装订:

@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;
 }
}
Run Code Online (Sandbox Code Playgroud)

商店装订:

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我将XML文件解组为fAollows:

  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
Run Code Online (Sandbox Code Playgroud)

当我打电话时,getBooks()我们得到空值.谁能发现我在这里做错了什么?!

bdo*_*han 5

由skaffman提供的答案是不正确.您可以在包级别通过@XmlSchema或在类级别指定命名空间,@XmlType并使用它来限定字段/属性:

欲获得更多信息