我正在使用javax.xml.bind.annotation,我需要获取属性“xmlns:language”(参见下面的xml)
<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;
}
答案 0 :(得分: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>