JAXB:如何将元素与命名空间绑定 [英] JAXB: How to bind element with namespace
本文介绍了JAXB:如何将元素与命名空间绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
他是我在远程机器上托管的XML:
He is my XML hosted on 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>
我的绑定书如下:
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;
}
}
商店绑定:
@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:
I am unmarshalling the XML
file as 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()
时,我们得到null值。谁能发现我在这里做错了什么?!
When I call getBooks()
we get null value. Can anyone spot what I am doing wrong here?!
推荐答案
由skaffman提供的答案不正确。您可以通过 @XmlSchema
在包级别指定命名空间,或者使用 @XmlType
在类级别指定命名空间并使其成为用于限定字段/属性:
The answer provided by skaffman is incorrect. You can specify the namespace at the package level via @XmlSchema
or at the class level using @XmlType
and have it be used to qualify the fields/properties:
更多信息
- http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
这篇关于JAXB:如何将元素与命名空间绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文