JAXB: how to associate an element with a namespace

It is my XML hosted on a remote machine:

<?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>

I have a binding book as follows:

Book binding:

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

Saving Binding:

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

I will format the file XMLas 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

When I call getBooks(), we get a null value. Can anyone determine what I'm doing wrong here?

+2
source share
2 answers

The answer provided by skaffman is incorrect. You can specify the namespace at the package level through @XmlSchemaor at the class level with @XmlTypeand use it to define fields / properties:

Additional Information

+5
source

100%, , , @XmlSchema (package-info.java).

+1

All Articles