对于具有命名空间的属性,JAXB返回null [英] JAXB returns null for attributes with a namespace
问题描述
我需要解组具有属性名称空间的XML,例如
I need to unmarshall an XML that has namespaces for the attributes, for instance
<license license-type="open-access" xlink:href="http://creativecommons.org/licenses/by/2.0/uk/"><license-p>
此属性定义为
@XmlAttribute(namespace = "http://www.w3.org/TR/xlink/")
@XmlSchemaType(name = "anySimpleType")
protected String href;
但是当我尝试检索href时,它为空。我应该添加/修改jaxb代码以获得正确的值?我已经尝试避免名称空间,但它不起作用,仍为null。我也试过 @XmlAttribute(namespace =http://www.w3.org/TR/xlink/,name =href)
但它没有用无论是。
But when I try to retrieve the href, it is null. What should I add/modify to the jaxb code in order to get the right value? I already tried to avoid namespaces but it did not work, still null. I also tried with @XmlAttribute(namespace = "http://www.w3.org/TR/xlink/", name = "href")
but it did not work either.
XML文件的顶部是:
The top of the XML file is:
<DOCTYPE article
PUBLIC "-//NLM//DTD v3.0 20080202//EN" "archive.dtd">
<article xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML" article-type="article">
推荐答案
以下是如何指定<$的示例 @XmlAttribute
注释中的c $ c> namespace 属性。
Below is an example of how to specify the namespace
property on the @XmlAttribute
annotation.
input.xml
<article xmlns:xlink="http://www.w3.org/1999/xlink">
<license xlink:href="http://creativecommons.org/licenses/by/2.0/uk/"/>
</article>
许可证
package forum10566766;
import javax.xml.bind.annotation.XmlAttribute;
public class License {
private String href;
@XmlAttribute(namespace="http://www.w3.org/1999/xlink")
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
文章
package forum10566766;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Article {
private License license;
public License getLicense() {
return license;
}
public void setLicense(License license) {
this.license = license;
}
}
演示
package forum10566766;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Article.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum10566766/input.xml");
Article article = (Article) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(article, System.out);
}
}
输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<article xmlns:ns1="http://www.w3.org/1999/xlink">
<license ns1:href="http://creativecommons.org/licenses/by/2.0/uk/"/>
</article>
想要控制命名空间前缀?
如果要控制将文档编组为XML时使用的名称空间前缀,请查看以下文章:
If you want to control the namespace prefixes used when the document is marshalled to XML check out the following article:
- http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
这篇关于对于具有命名空间的属性,JAXB返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!