简体   繁体   English

如何从Java中的对象列表创建XML文件?

[英]How to create XML file from a list of objects in Java?

I want to create one XML file from one list of objects. 我想从一个对象列表创建一个XML文件。 Objects are having some attributes, so the tags will be the attribute names and the respective data will be inside the tag. 对象具有一些属性,因此标记将是属性名称,相应的数据将位于标记内。

This is example: 这是一个例子:

I have one List myEquipmentList , that contains 100 objects of the class Equipment . 我有一个List myEquipmentList ,它包含类Equipment 100个对象。 Now, the attributes in the class of Equipment are id, name, size, measures, unit_of_measure etc. 现在, Equipment类中的属性是id,name,size,measure,unit_of_measure等。

Now I want to create XML which will be something like this. 现在我想创建类似这样的XML。

<Equipment id=1>``
<name>Ruler</name>
<size>1000</size>
<measures>length</measures>
<unit_of_measure>meter</unit_of_measure>
</Equipment>

Any ideas? 有任何想法吗?

you can create a class with the list of objects, then serialise the list to xml and finally deserialise xml to a list. 您可以使用对象列表创建一个类,然后将列表序列化为xml,最后将xml反序列化为列表。

Please see this link - Very useful: How to convert List of Object to XML doc using XStream 请参阅此链接 - 非常有用: 如何使用XStream将对象列表转换为XML文档

Read about JAXB. 阅读JAXB。

You could have a class like this that would generate the XML you want: 你可以有一个这样的类来生成你想要的XML:

@XmlRootElement
public class Equipment {
  private Long id;
  private String name;
  private Integer size;
  ...etc...

  @XmlAttribute
  public Long getId() {
     return id;
  }

  public void setId(Long id) {
     this.id = id;
  }

  @XmlElement
  public String getName() {
    return name;
  }

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

  ... etc...

}

You'll find plenty of info on JAXB on google on searching on stackoverflow. 你可以在谷歌搜索stackoverflow上找到关于JAXB的大量信息。

http://jaxb.java.net/ http://jaxb.java.net/

http://jaxb.java.net/tutorial/ http://jaxb.java.net/tutorial/

These look like a couple of simple tutorials: 这些看起来像几个简单的教程:

http://www.mkyong.com/java/jaxb-hello-world-example/ http://www.mkyong.com/java/jaxb-hello-world-example/

http://www.vogella.com/articles/JAXB/article.html http://www.vogella.com/articles/JAXB/article.html

One of the easiest ways to do this is simply iterate over the list and use strings to write the XML. 最简单的方法之一就是遍历列表并使用字符串来编写XML。 Nothing special, very quick and easy. 没有什么特别的,非常快速和简单的。

I tend to use a library called Simple XML Serialization over JAXB, and I have to say it's pretty simple, yet extremely flexible. 我倾向于使用一个名为Simple XML Serialization的库而不是JAXB,我不得不说它非常简单,但非常灵活。

There's good comparison between Simple and JAXB here . Simple和JAXB 在这里有很好的比较。

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

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