xml java类_将xml表示为java类

注意:我是

EclipseLink JAXB (MOXy)领导者,也是

JAXB (JSR-222)专家组的成员.

IS there a way to generate java classes dynamicaly for a structure

like this ?

JAXB实现提供了从XML模式生成Java模型的能力.从Java SE 6开始的JDK中包含的参考实现可在以下位置获得:

/bin/xjc

可以在此处找到从XML模式生成对象模型的示例:

A small correction,i don’t have an xsd for the xml

如果您没有XML模式,您可以找到一个实用程序来从XML文档生成XML模式:

或者从代码开始.

从代码开始

您还可以从代码开始并注释模型以映射到现有的XML结构.

package forum11213872;

import java.util.List;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="Root")

@XmlAccessorType(XmlAccessType.FIELD)

public class Root {

@XmlElement(name="Book")

private List books;

}

package forum11213872;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)

public class Book {

@XmlAttribute

private String name;

@XmlAttribute

private int price;

}

演示

package forum11213872;

import java.io.File;

import javax.xml.bind.*;

public class Demo {

public static void main(String[] args) throws Exception {

JAXBContext jc = JAXBContext.newInstance(Root.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();

File xml = new File("src/forum11213872/input.xml");

Root root = (Root) unmarshaller.unmarshal(xml);

Marshaller marshaller = jc.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);

marshaller.marshal(root,System.out);

}

}

input.xml中/输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值