title: How do I programmatically create XML from Java?
body: <p>I am trying to programmatically create XML elements using JAXB in Java. Is this possible? I am reading this page <a href="https://jaxb.java.net/nonav/2.2.5-5/docs/ch03.html#marshalling-element-default-values-and-marshalling" rel="nofollow">here</a> for something I can use, but have so far found nothing. </p>
  
  <p>Usually you start by defining a bean</p>
  
  <pre><code>@XmlRootElement public class MyXML { 
    private String name;
    public String getName() {  return name; }
    @XmlElement public void setName(String s) { this.name = s; }
  }
  </code></pre>
  
  <p>and serialize it with code like</p>
  
  <pre><code>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"));
    }
  }
  </code></pre>
  
  <p>that whould produce the following XML </p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
  &lt;myXML&gt;
      &lt;name&gt;Yo&lt;/name&gt;
  &lt;/myXML&gt;
  </code></pre>
  
  <p>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?</p>