如何解析xml到java对象? [英] how to parse xml to java object?

查看:176
本文介绍了如何解析xml到java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于配置一些规则的XML,它没有复杂的结构,但是这个配置在我的系统中的任何地方使用,所以我想将这个XML解析为java对象并设计为单例模式,是任何好的方法我可以用它来直接解析XML到Java对象而不需要写很多代码吗?

I have a XML which is used to config some rules, it does not has complex structure, but this configuration is used anywhere in my system, so I want to parse this XML to java object and design as singleton mode, is any good way I can use it to unmarshal XML to Java object directly without write much codes?

我做了一些关于谷歌的研究,知道JAXB是一个选择,我的应用程序只是某些工具程序读取规则然后跟踪做什么,JAXB可以更广泛地用于Web服务,它适合我的项目?

I did some research on Google and known JAXB is a choice, my application is just some kinds of tool program which read rule and then follow do stuffs, JAXB could be used for web service more widely, it fit my projects?

如果是,最重要的问题是,我用xjc根据xsd文件生成java对象的源类,解组之后我会直接得到这些configurationType对象,是否有必要我再次转换,(从JaxB类到我拥有的java pojo对象配置),我看到大多数编码器做了这个,但为什么呢?因为它们是一些数据,只是从生成到JAXB的对象和复制到自己创建的POJO对象

If yes, the most important question is, I used xjc to generate java object source class according xsd file, after unmarshal I will directly get these configurationType object, is it necessary I convert again, (from the JaxB classes to my owned java pojo object configuration), I see most coder did this, but why? because they are some data, just from the object generated to JAXB and copy to ourself created POJO object

推荐答案

JAXB是一个理想的解决方案。但是你不一定需要xsd和xjc。通常你没有xsd,但你知道你的xml是什么。只需分析您的xml,例如,

JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,

<customer id="100">
    <age>29</age>
    <name>mkyong</name>
</customer>

创建必要的模型类:

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

尝试解组:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));

检查结果,修复错误!

这篇关于如何解析xml到java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆