如何从对象层次结构生成xml?

时间:2009-11-26 13:28:14

标签: java xml xml-serialization

我有对象,树/模型/层次结构,无论正确的术语是什么。它由可以表征为所需XML的一对一映射的内容组成。

这就是我有以下内容(使用非标准的UML语法)

class A {
    class B b[*]
    class C
    class D
}

class B {
    class C c[*]
    string AttributeFoo = "bar"
}

class C {
    string AttributeThis = "is"
}

class D {
    string AttributeName = "d"
}

所需的输出是这样的:

<?xml version="1.0"?>
<a>
    <b attribute-foo="bar">
        <c attribute-this="is"/>
    </b>
    <c attribute-this="is"/>
    <d attribute-name="d"/>
</a>

您有什么建议成为实现此目标的最佳和/或最简单方式?

6 个答案:

答案 0 :(得分:3)

最简单的方法是使用XStream。请参阅here了解它的作用。它可能有点儿麻烦,但对于简单的任务它很棒。对于更全面(和可靠)的技术,JAXB(Java6的一部分,请参阅javax.xml.bind)是更好的选择。

答案 1 :(得分:3)

我认为JAXB(http://jaxb.java.net/)的目的是将对象映射到XML /从XML

答案 2 :(得分:3)

我会看JAXB因为 a)你在标准库中得到它而 b)它并不复杂。此代码需要Java 6:

@XmlRootElement public static class A {
  public List<B> b = new ArrayList<B>();
}

public static class B {
  public List<C> c = new ArrayList<C>();
  @XmlAttribute(name = "attribute-foo") public String attributeFoo = "foo";
}

public static class C {
  @XmlAttribute(name = "attribute-this") public String attributeThis = "is";
}

public static void main(String[] args) {
  A a = new A();
  a.b.add(new B());
  a.b.get(0).c.add(new C());
  JAXB.marshal(a, System.out);
}
//TODO: getters/setters, error handling and so on

输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
    <b attribute-foo="foo">
        <c attribute-this="is"/>
    </b>
</a>

答案 3 :(得分:2)

如果您想使用工具,请查看jaxb。编组/解编是您在这里所做的事情,这是许多解决方案的常见问题。

我认为这是最好的(不是重新发明轮子)而且它是最简单的(我手动完成它并没有什么乐趣 - 对象图可以是循环的......)

答案 4 :(得分:1)

我喜欢XMLBeans

答案 5 :(得分:1)

在我看来,如果你对性能不太感兴趣,我会远离Jaxb,看看一些更简单的框架。如果性能是一个问题,我倾向于在大多数情况下支持jibx而不是jaxb。

在这种情况下,我倾向于使用简单的项目。

http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#start

只是注释你的对象模型,然后你走了.....: - )

@Root
public class Example {

   @Element
   private String text;

   @Attribute
   private int index;

   public Example() {
      super();
   }  

   public Example(String text, int index) {
      this.text = text;
      this.index = index;
   }

   public String getMessage() {
      return text;
   }

   public int getId() {
      return index;
   }
}
相关问题