2012-05-12 16 views
5

我需要來解讀是有屬性命名空間的XML與命名空間屬性返回null,例如JAXB爲

<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"> 
+0

什麼是XML文件的頂部是什麼樣子? –

回答

3

下面是如何指定的@XmlAttribute註解namespace屬性的示例。

的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看看下面的文章命名空間前綴:

+1

問題在於原始代碼中的命名空間,代碼中是'http://www.w3.org/TR/xlink/',但是'http://www.w3.org/1999/xlink'中的代碼是'http://www.w3.org/TR/xlink/' xml。 @ blaise-doughan的回答幫助我意識到問題所在。謝謝 – ljgc