例如,我需要解码具有属性命名空间的 XML
<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 代码添加/修改什么以获得正确的值?我已经尝试过避免命名空间,但它没有用,仍然是空的。我也尝试过 @XmlAttribute(namespace = "http://www.w3.org/TR/xlink/", name = "href")
但它也没有用。
XML 文件的顶部是:
<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
注释上指定 namespace
属性的示例。
输入.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 时使用的 namespace 前缀,请查看以下文章:
关于java - JAXB 为具有命名空间的属性返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10566766/