user3808269
user3808269

Reputation: 1351

How do I programmatically create XML from Java?

I am trying to programmatically create XML elements using JAXB in Java. Is this possible? I am reading this page here for something I can use, but have so far found nothing.

Usually you start by defining a bean

@XmlRootElement public class MyXML { 
  private String name;
  public String getName() {  return name; }
  @XmlElement public void setName(String s) { this.name = s; }
}

and serialize it with code like

public class Serializer { 
  static public void main(String[] args) { 
     MyXML m = new MyXML();
     m.setName("Yo");
     JAXBContext jaxbContext = JAXBContext.newInstance(MyXML.class);
     Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
     jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
     jaxbMarshaller.marshal(m, new File("MyXML_"+ ".xml"));
  }
}

that whould produce the following XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myXML>
    <name>Yo</name>
</myXML>

How would I program my Java class to create the element tag name depending on what is entered in the program? For instance in my example the tag element is called 'name'. How could I set this at runtime though? Is this possible with generics or some other way?

Upvotes: 1

Views: 1106

Answers (2)

Raffaele
Raffaele

Reputation: 20885

The B in JAXB stands for Bean so no, there's no way to use JAXB without defining beans.

You just want to dinamically create an XML so take a look at jOOX for example (link to full Gist)

Document document = JOOX.builder().newDocument();
Element root = document.createElement("contacts");
document.appendChild(root);

for (String name : new String[]{"John", "Jessica", "Peter"}) {
  $(root).append(
    $("contact"
      , $("name", name)
      , $("active", "true")
    )
  );
}

Upvotes: 1

strexxx
strexxx

Reputation: 11

Here, you use annotation before compile-time while you have no knowledge yet of the format you will need.. Marshalling this way is not that different from serializing, and it basically map directly the fields of a java object to an XML representation --> (if something is not defined in the object, it won't appear in the representation). What you thrive to do looks like simple xml crafting (a XML parser would be enough S(t)AX/DOM whatever -- I like Jackson).

For the sake of curiosity, if you really want to fiddle with annotation you can use a bit of reflection in conjonction with the answer you will find here

Upvotes: 0

Related Questions