如何获取属性值?(javax.xml.bind.annotation)

时间:2013-05-26 09:44:40

标签: java xml jaxb

我正在使用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;
}

1 个答案:

答案 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>
相关问题