1

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

1 回答 1

0

在您问题的文档中,您声明前缀language将与 namespace 相关联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>
于 2013-05-26T20:17:33.403 回答