JAXB动态添加元素

时间:2015-11-03 07:41:35

标签: java xml jaxb

是否可以通过JAXB以这种方式创建XML Document。 由于副本介于mkdir之间,因此它将是动态的

<project>
    <create>
        <mkdir dest="src/java"/>
        <copy src="test/src/java" dest="src/java" />
        <mkdir dest="{projectPath}/web/META-INF"/>
    </create>
</project>

我的java代码: -

@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;

   .....
}

我可以通过JDOM实现相同目的,但我想通过Java Object实现它。

或者我应该使用任何其他Java库。

1 个答案:

答案 0 :(得分:0)

您应该在类Create:

上使用此注释
@XmlAccessorType(XmlAccessType.FIELD)
public class Create { ... }

假设您没有显示的类(Tree,Buildfile,Mkdir,...)中没有毛刺,您可以使用以下代码(其中String用作替代我不知道的所有类)来编组XML文件:

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

输出:

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

我想mkdirs都可以在前面。如果 要混合,那就更复杂了。

编辑您需要一个能够保存混合类型元素的列表,这是常见类型的最佳子类型。

@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; }
}

输出:

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