简体   繁体   English

从Java对象创建xml文件

[英]Create xml file from java object

  1. I want to create an XML file from java 6 (it's the first time I want to try that) and I would like an example of how can I do that with DOM. 我想从Java 6创建XML文件(这是我第一次尝试这样做),并且我想举一个如何使用DOM的示例。 I need an example showing how to build tree? 我需要一个示例来说明如何构建树?
  2. Can I create an EDMX file from a java object ? 我可以从Java对象创建EDMX文件吗?

Regards, Boris 鲍里斯

Simplest example of convert java object to xml is this: 将Java对象转换为xml的最简单示例是:

@XmlRootElement( name = "entity")
public class Entity {

    private int age = 22;
    private String firstname = "Michael";

    public int getAge() {
        return age;
    }

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

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname( String firstname ) {
        this.firstname = firstname;
    }
}

public class Main {
    public static void main( String[] args ) {
        JAXBContext jc = JAXBContext.newInstance( Entity.class );
        Marshaller m = jc.createMarshaller();
        m.marshal( new Entity(), System.out );
    } 
}

Will print to the console this: 将打印到控制台:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><entity><age>22</age><firstname>Michael</firstname></entity>

If you need to serialize java objects to XML file - just feed them to XStream ! 如果需要将Java对象序列化为XML文件,只需将它们提供给XStream It works both ways. 它可以双向工作。 Code snippets here . 此处的代码段。

Good luck! 祝好运!

它认为您应该使用JAXBJAXP ,这将使您的生活比使用DOM更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM