本文介绍了使用JAXB进行XML解组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,我正在试图解组,但我无法弄清楚如何去做。

I have an XML file that I'm trying to unmarshal, but I cant figure out how to do it.

XML看起来像

<config>
    <params>
        <param>
            <a>draft</a>
            <b>Serial</b>
        </param>
        <param>
            <a>amt</a>
            <b>Amount</b>
        </param>
    </params>
    <server>
        <scheme>http</scheme>
        <host>somehost.com/asdf</host>
    </server>
</config>

当我将params作为根元素并且没有服务器元素或配置时,我以前可以解组根元素。

I could previously unmarshall when I had params as the root element and didnt have the server elements or config as root element.

我添加了一个配置类来尝试取消编组,但我不知道我哪里出错了。

I added a config class to try to unmarshall this, but I dont know where I'm going wrong.

我的课程看起来像

@XmlRootElement
public class Config {

    private Params params = new Params();

    @XmlElement(name="params")
    public Params getParams() {
        return params;
    }
    public void setParam(Params params) {
        this.params = params;
    }
}

public class Params {
    private List<Param> params = new ArrayList<Param>();

    public List <Param> getParam() {
        return params;
    }

    public void setParam(List<Param> params) {
        this.params = params;
    }
}

public class Param {
    String a;
    String b;
    //getters and setters.  omitted for brevity
}

解组码

File file = new File("C:\\config.xml");
InputStream inputStream = new FileInputStream(file);
JAXBContext jc = JAXBContext.newInstance(Config.class);
Unmarshaller u = jc.createUnmarshaller();
conf = (Config) u.unmarshal(file);
System.out.println(conf.getParams().getParam().size());

println打印0.我哪里出错?

the println prints 0. Where did I go wrong?

我知道我还没有任何服务器节点的代码,还没有到那里。我的实际XML还没有那个节点,我仍然无法在config标签内正确解组params。

I know I dont have any code for the server nodes yet, havent gotten there yet. My actual XML doesnt have that node yet and I still cant get it to unmarshall the params correctly when inside the config tag.

推荐答案

您只需要进行以下更改即可。将Config中的setParams方法更改为

You just need to do following changes and it will work. Change setParams method in Config to

@XmlElement(name = "params") //<--Annotation added here
public void setParam(Params params) {
    this.params = params;
}

这篇关于使用JAXB进行XML解组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:49