1

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?

2 Answers 2

1

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")
    )
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is an example of how to use jOOX? 0_o
Yes, it is. What's the problem?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.