将xml表示为java类

可能这个问题可能会被问到.我是将xml转换为 java类的新手.
我有一个像这样的xml:

<Root>
    <Book name="harel" price="5" />
    <Book name="xml" price="9" />
</Root>

有没有办法为这样的结构动态生成java类?
 一个小的修正,我没有xml的xsd

解决方法

注意:我是 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中包含的参考实现可在以下位置获得:

<JAVA_HOME>/bin/xjc

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

> http://blog.bdoughan.com/2010/09/processing-atom-feeds-with-jaxb.html

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

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

> Any tools to generate an XSD schema from an XML instance document?

或者从代码开始.

从代码开始

您还可以从代码开始并注释模型以映射到现有的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<Book> 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中/输出

<Root>
    <Book name="harel" price="5" />
    <Book name="xml" price="9" />
</Root>

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念