简体   繁体   English

如何更新JAXB中的特殊元素?

[英]How I can update special element in JAXB?

I used Jaxb for read and write from my XML File.I want update spacial element in my XML, but I don't know how can do that in my code,any body you can till me how I can do that. 我使用Jaxb来读取和写入XML文件。我想更新XML中的空格元素,但是我不知道如何在我的代码中做到这一点,任何人只要我能做到这一点就可以。 That my update method 那我的更新方法

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

My XML file: 我的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>

NOTE: For example I need change value in LayerName from a -->b but just in IdLayer="2" (In my code I can't select my element which I want update).Please any way for do that!!!! 注意:例如,我需要从-> b的LayerName更改值,而仅在IdLayer="2"IdLayer="2" (在我的代码中,我无法选择要更新的元素)。请以任何方式这样做!!! !

Once you have unmarshalled the XML, you should perform the following check 解组XML后,应执行以下检查

// unmarshal Project
for(Layer layer : project.getLayer()) {
    if (layer.getIdLayer().equals("2")) {
        layer.setLayerName("b");
    }
}
// marshal Project back to XML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM