如何将元素添加到XML文件?

时间:2014-04-06 21:32:32

标签: java xml jaxb2

我在生成我的类时使用了JAXB但是在我的XML文件中插入元素时遇到问题,所以我在我的文件XML中插入了第一个时间元素,但是当第二次插入时,所有文件都清晰并重新编写XML。 我有类(项目,层),我是写插入项目和图层到XML文件的方法。 请帮助我如何在XML中插入项目,然后在每次编写XML时使用明确的xml文件在XML中插入图层。

这是我的班级项目:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Project")
public class Project {

    @XmlElement(name = "Layer")
    protected List<Layer> layer;
    @XmlAttribute(name = "name")
    protected String name; 

   public List<Layer> getLayer() {
        if (layer == null) {
            layer = new ArrayList<Layer>();
        }
        return this.layer;
    }
    public String getName() {
        return name;
    }
    public void setName(String value) {
        this.name = value;
    }
}

这是我的班级图层:

@XmlAccessorType(XmlAccessType.FIELD)
public class Layer {
    @XmlElement(name = "LayerName", required = true)
    protected String layerName;
    @XmlAttribute(name = "idLayer")
    protected int idLayer;
    public String getLayerName() {
        return layerName;
    }
    public void setLayerName(String value) {
        this.layerName = value;
    }
    public int getIdLayer() {
        return idLayer;
    }
    public void setIdLayer(int i) {
        this.idLayer = i;
    }
}

方法插入项目:

  public boolean Insert(Project entity) {
    Project pr = new Project();
    pr.setName(entity.getName());
    try {
         JAXBContext jc = JAXBContext.newInstance(Project.class);
         javax.xml.bind.Marshaller marshaller = jc.createMarshaller();
         marshaller.setProperty(marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
         File XMLfile = new File("Projects//asdad//ProjectDataBase.xml");
         marshaller.marshal(pr, XMLfile);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return false;
}

方法插入图层:

  public boolean Insert(Layer entity) {
    Project pr = new Project();
    pr.setName(pr.getName());
    Layer addLayer = new Layer();
    addLayer.setIdLayer(entity.getIdLayer());
    addLayer.setLayerName(entity.getLayerName());
    pr.getLayer().add(addLayer);

    try {
         JAXBContext jc = JAXBContext.newInstance(Project.class);
         javax.xml.bind.Marshaller marshaller = jc.createMarshaller();
         marshaller.setProperty(marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
         File XMLfile = new File("Projects//asdad//ProjectDataBase.xml");
         marshaller.marshal(pr, XMLfile);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return false;
}

0 个答案:

没有答案