使用JAXB解组并不起作用

时间:2014-10-29 16:29:33

标签: java xml jaxb

我有一个简单的XML,我想要解组成一个模型类。我用JAXB注释注释了类,用于定义访问类型(FIELD):

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlAccessorType(XmlAccessType.FIELD)
public class DtoTest {

    private String name;

    public DtoTest() {}

    public DtoTest(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "DtoTest [name=" + name + "]";
    }
}

这是我的主类,我对一个保存在String变量中的简单XML运行一个unmarshal方法:

public class Test {

    public static void main(String[] args) throws Exception {
        Object obj = new DtoTest();
        String testXML = "<dtoTest><name>example</name></dtoTest>";
        obj = unmarshal(obj, testXML);
        System.out.println(obj);
    }

    /* This is a generic unmarshall method which I've already used with success with other XML*/
    public static <T> T unmarshal(T obj, String xml) throws Exception {
        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));

        Class<? extends Object> type = obj.getClass();
        JAXBContext jc = JAXBContext.newInstance(type);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        obj =  (T)unmarshaller.unmarshal(xsr, type).getValue();
        xsr.close();

        return obj;
    }
}

每当我运行代码时,我都得到相同的输出:

DtoTest [name=null]

我不明白我做错了什么。

2 个答案:

答案 0 :(得分:2)

我只是在jdk1.7.0_67上运行你的代码并且它可以运行。

DtoTest [name=example]

也许你对包含的库有些问题?我只使用普通的java运行它。

答案 1 :(得分:1)

你的问题对我来说完全没问题。您可以对其进行的一项优化是创建StreamSource而不是XMLStreamReader

import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

public class Test {

    public static void main(String[] args) throws Exception {
        Object obj = new DtoTest();
        String testXML = "<dtoTest><name>example</name></dtoTest>";
        obj = unmarshal(obj, testXML);
        System.out.println(obj);
    }

    public static <T> T unmarshal(T obj, String xml) throws Exception {
        StreamSource source = new StreamSource(new StringReader(xml));

        Class<? extends Object> type = obj.getClass();
        JAXBContext jc = JAXBContext.newInstance(type);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        obj =  (T)unmarshaller.unmarshal(source, type).getValue();

        return obj;
    }

}

调试提示

当解组不按预期工作时,填充JAXB模型并将其封送到XML以查看预期的XML是什么样的。