【问题标题】:JAXB: How to bind element with namespaceJAXB:如何将元素与命名空间绑定
【发布时间】:2011-11-07 15:47:07
【问题描述】:

他是我在远程机器上托管的 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 文件解组为 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

当我调用getBooks() 时,我们得到空值。谁能发现我在这里做错了什么?!

【问题讨论】:

    标签: java xml jaxb


    【解决方案1】:

    answer provided by skaffman 不正确。您可以通过@XmlSchema 在包级别指定命名空间,或者使用@XmlType 在类级别指定命名空间,并使用它来限定字段/属性:

    更多信息

    【讨论】:

    • +1。 XJC 将在为绑定文件中的模式提供包名称时使用此机制。至少在 JAXB 2.1 RI 以后的这些条件下,我一直看到它在 package-info.java 上使用 @XmlSchema。
    【解决方案2】:

    我不是 100% 确定,但我认为可以通过在包级别 (package-info.java) 上使用 @XmlSchema 注释来省略这种重复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多