Is it possible to create XML Document by JAXB in such way. As copy is between mkdir and it will be dynamic
<project>
<create>
<mkdir dest="src/java"/>
<copy src="test/src/java" dest="src/java" />
<mkdir dest="{projectPath}/web/META-INF"/>
</create>
</project>
My java Code :-
@XmlRootElement(name = "project")
public class Project {
private Create create;
private Tree tree;
public Create getCreate() {
return create;
}
public void setCreate(Create create) {
this.create = create;
}
public Tree getTree() {
return tree;
}
public void setTree(Tree tree) {
this.tree = tree;
}
}
@XmlRootElement
public class Create {
private List<Mkdir> mkdir;
private Buildfile buildfile;
private Createfile createfile;
private Execute execute;
private Copy copy;
.....
}
I am able to achieve same by JDOM but i want to do it by Java Object.
Or i should use any other Java Library for this.
You should use this annotation on class Create:
@XmlAccessorType(XmlAccessType.FIELD)
public class Create { ... }
Assuming there are no glitches in the classes you haven't shown (Tree, Buildfile, Mkdir,...) you can use the following code (where String serves as a replacement for all classes unknown to me) to marshal an XML file:
void marshal() throws Exception { Project root = new Project(); Create create = new Create(); root.setCreate( create ); create.getMkdir().add( "make dir1" ); create.getMkdir().add( "make dir2" ); create.setBuildfile( "buildfile1" ); create.setCreatefile( "createfile1" ); JAXBContext jc = JAXBContext.newInstance( Project.class ); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal( root, System.out ); }
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<project>
<create>
<mkdir>make dir1</mkdir>
<mkdir>make dir2</mkdir>
<buildfile>buildfile1</buildfile>
<createfile>createfile1</createfile>
</create>
</project>
I suppose the mkdirs can all be up front. If it has to be mixed, it's a little more complicated.
Edit You need a list capable of holding elements of mixed types, best subtypes of a common type.
@XmlAccessorType(XmlAccessType.FIELD) public class Create { @XmlElements({ @XmlElement(name = "mkdir", type = MkdirCommand.class), @XmlElement(name = "copy", type = CopyCommand.class) }) private List cmds; public List getCmds(){ if( cmds == null ) cmds = new ArrayList(); return cmds; } } class Command { } class MkdirCommand extends Command { @XmlAttribute public String dest; public MkdirCommand( String d ){ dest = d; } } class CopyCommand extends Command { @XmlAttribute public String src; @XmlAttribute public String dest; public CopyCommand( String s, String d ){ src = s; dest = d; } }
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<project>
<create>
<mkdir dest="foo/dir1"/>
<copy src="source" dest="target"/>
<mkdir dest="bar/dir2"/>
</create>
</project>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments