我使用Jaxb
从我的XML文件中读取和写入。我想在我的XML中更新空间元素,但我不知道如何在我的代码中执行此操作,您可以使用任何正文我该怎么做
我的更新方法
public boolean Update(Layer entity) {
try {
File file = new File(Test.PathXMl);
//read from my xml
JAXBContext jaxbContext = JAXBContext.newInstance(Project.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Project project = (Project) jaxbUnmarshaller.unmarshal(file);
// here update my XML new value but not special element
Layer layer = new Layer();
layer.setLayerName(entity.getLayerName());
layer.setOrder(entity.getOrder());
layer.setVisible(entity.isVisible());
project.getLayer().add(layer);
//write in xml file
ObjectFactory objectFactory = new ObjectFactory();
javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(project, new FileOutputStream(Test.PathXMl));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
return false;
}
我的XML文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Project xmlns="http://www.example.org/ProjectDataBase" name="name1">
<Layer idLayer="2">
<LayerName>a</LayerName>
<Order>2</Order>
<Visible>false</Visible>
</Layer>
<Layer idLayer="1">
<LayerName>add</LayerName>
<Order>1</Order>
<Visible>true</Visible>
</Layer>
</Project>
注意:例如,我需要更改LayerName
中的值 - >&gt; b但是只需IdLayer="2"
(在我的代码中我无法选择我要更新的元素)请以任何方式做到这一点!!!!
答案 0 :(得分:0)
一旦解组了XML,就应该执行以下检查
// unmarshal Project
for(Layer layer : project.getLayer()) {
if (layer.getIdLayer().equals("2")) {
layer.setLayerName("b");
}
}
// marshal Project back to XML