mardi 31 mars 2015

How to programmatically marshall XML from Java - 0_o


Vote count:

0




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.


Normally I have to hard-code the element value like so:



import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
class MyXML {

String name;

public String getName() {
return name;
}

@XmlElement
public void setName(String s) {
this.name = s;
}

}//end class


Below is the calling class to write this to XML (marshall it):



import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;

public class Foo {

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"));



}

} //end Foo class


This would produce an XML document like so:



<?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?


Respectfully,



asked 19 secs ago







How to programmatically marshall XML from Java - 0_o

Aucun commentaire:

Enregistrer un commentaire