Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何更新JAXB中的特殊元素?_Java_Xml_Jaxb - Fatal编程技术网

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

Java 如何更新JAXB中的特殊元素?,java,xml,jaxb,Java,Xml,Jaxb,我使用Jaxb从我的XML文件读写。我想在我的XML中更新空间元素,但我不知道如何在我的代码中做到这一点,任何人都可以,直到我知道我如何做到这一点。 这是我的更新方法 public boolean Update(Layer entity) { try { File file = new File(Test.PathXMl); //read from my xml JAXBContext jaxbContext = JAXBContext.newInstance(Project.

我使用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>

注意:例如,我需要从a->b更改LayerName中的值,但仅在IdLayer=2中,在我的代码中,我无法选择我要更新的元素。请以任何方式进行更新

一旦对XML进行了解组,就应该执行以下检查

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

在我的代码中,我无法选择我想要更新的元素-你是说你不知道如何更新,还是因为某种原因不允许更新?Layer类是否有方法getIdLayer和setIdLayer?而且你似乎没有在项目上设置Layer实例?jon:我是说我不知道如何设置。我无法为updatejamab选择特殊元素:层有方法getIdLayer和setIdLayer。非常感谢您的帮助