2013-05-26 104 views
1

進出口使用javax.xml.bind.annotation,我需要得到屬性?「的xmlns:語言」(見下面的XML)我怎樣才能獲得屬性值(javax.xml.bind.annotation)

<type xmlns:language="ru" xmlns:type="string">Some text</type> 

我應該使用什麼註釋?

@XmlRootElement(name = "type") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Type { 
    @XmlValue 
    protected String value; 

    @XmlAttribute 
    protected String language; 
} 
+5

'xmlns:language'不是一個屬性,它是一個名稱空間綁定。您將名稱空間'ru'綁定到名稱空間前綴'language'。這真的是你想要做的嗎? –

+1

如果你有對XML格式的控制,那麼爲此目的使用'xml:lang'屬性而不是命名空間聲明會更合適。 –

回答

0

在從你的問題你宣佈前綴language將與命名空間ru相關文檔。

<type xmlns:language="ru" xmlns:type="string">Some text</type> 

我不相信以上就是你要做的。如果您正在嘗試爲文檔指定語言,我建議使用xml:lang屬性來代替(如Ian Roberts所建議的)。

<type xml:lang="ru">Some text</type> 

類型

那麼你將映射到它使用@XmlAttribute註解如下:

import javax.xml.bind.annotation.*; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Type { 

    @XmlValue 
    protected String value; 

    @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") 
    protected String language; 

} 

演示

import java.io.StringReader; 
import javax.xml.bind.*; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Type.class); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     StringReader xml = new StringReader(
       "<type xml:lang='ru' xmlns:type='string'>Some text</type>"); 
     Type type = (Type) unmarshaller.unmarshal(xml); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(type, System.out); 
    } 

} 

輸出

<?xml version="1.0" encoding="UTF-8"?> 
<type xml:lang="ru">Some text</type>