How can I generate xml from an object hierarchy?

I have an object, tree / model / hierarchy, regardless of the correct term. It consists of what can be described as a one-to-one mapping of the desired XML.

That is, I have the following (in custom syntax like 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"
}

The desired output looks something like this:

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

What would you suggest the best and / or simplest way to achieve this?

+3
source share
6 answers

I would look at JAXB because: a) you will get it in the standard library and b) it is not that difficult. This code requires 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

Output:

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

- XStream. , . , . ( ) JAXB ( Java6, . javax.xml.bind) .

+3

, JAXB (http://jaxb.java.net/) / XML

+3

, jaxb. Marshalling/Unmarshalling - , , .

, ( ), ( , - ...)

+2
+1

In my opinion, if you weren’t too worried about performance, I would stay away from Jaxb and take a look at some of the simpler frameworks. If performance is a problem, I prefer jibx over jaxb for most situations.

In this situation, I try to use a simple project.

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

Just comment on your object model and off you go ..... :-)

@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;
   }
}
+1
source

Source: https://habr.com/ru/post/1724005/


All Articles