简体   繁体   English

如何通过RESTful Web服务-JAX-RS使用JAXB更新XML元素列表?

[英]How to Update List of XML element using JAXB via RESTful Web Services- JAX-RS?

I have an XML file that generated by JAXB. 我有一个JAXB生成的XML文件。 what I expected to do is put "Add and Update" operation within single method. 我期望做的是将“添加和更新”操作放在单个方法中。 "Add" operation works to append new entry/element but failed to update the existing item properly. “添加”操作可以附加新的条目/元素,但无法正确更新现有项目。

If I want to change the id value of "Damien" to "P005", it will create new element with same name but different id (Damien, P005). 如果要将“ Damien”的id值更改为“ P005”,它将创建名称相同但ID不同(Damien,P005)的新元素。 the previous value still there (Damien, P004). 以前的值仍然存在(Damien,P004)。

Any suggestion ? 有什么建议吗? Thanks before. 之前谢谢。

here the XML file 这是XML文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<getPersonsData>
   <person>
      <name>Alice</name>
      <id>P001</id>
   </person>
   <person>
      <name>Bob</name>
      <id>P002</id>
   </person>
   <person>
       <name>Charlie</name>
       <id>P003</id>
   </person>
    <person>
       <name>Damien</name>
       <id>P004</id>
    </person>

</getPersonsData>

here the JAXB class of Person 这是PersonJAXB

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"id"
 })
 @XmlRootElement(name = "person")
 public class Person {

  @XmlElement(required = true)
  protected String name;
  @XmlElement(required = true)
  protected String id;

 public String getName() {
    return name;
 }


 public void setName(String value) {
    this.name= value;
 }


 public String getId() {
    return id;
 }


 public void setid(String value) {
    this.id = value;
 }

 }

here the JAXB class of GetPersonsData 这是GetPersonsDataJAXB

  @XmlAccessorType(XmlAccessType.FIELD)
  @XmlType(name = "", propOrder = {
  "person"
  })
  @XmlRootElement(name = "getPersonsData")
  public class GetPersonsData {

@XmlElement(name="person", required = true)
    protected List<Person> person;


    public List<Person> getPersons() {
    if (person == null) {
        person = new ArrayList<Person>();
    }
    return this.person;
    }
 }

here the RESTFul Web Service (JAX-RS) class 这里是RESTFul Web服务(JAX-RS)

@Path("/rest")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON)
public class PersonConfig{        

     /**
 * POST Method to add/update name and id
 * 
 */
@POST
@Path("/saveperson")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED,
        MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON)
public void savePerson(@FormParam("name") String name,
        @FormParam("id") String id) {


    try {

        String tesfile = "root/data/person.xml";
        File file = new File(tesfile);


        JAXBContext jc = JAXBContext.newInstance(GetPersonsData.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        // unmarshalling xml file
        GetPersonsData getPersonsData = (GetPersonsData) unmarshaller
                .unmarshal(file);

        // get list of persons
        List<Person> listPerson = getPersonsData.getPersons();
        Iterator<Person> iter = listPerson.iterator();
        Person  person  = iter.next();


                 //if person not exist, append new entry (element) to xml
                 //this code works, but I failed to update the existing 
                 //element.
                 //If I want to update the id or name that already exist  
                 //it will create new person with same name but different id and 
                 //vice versa.
             if(!person.getName().equals(name)){
                Person p = new Person();
                p.setName(name);
                p.setId(id);
                listPerson.add(p);
         }else if (!person.getId().equals(id){
                     person.setId(id);
                 }


        // Marshalling Object to the xml file
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(getConfigInputType, file);
        m.marshal(getConfigInputType, System.out);

    } catch (ParserConfigurationException e) {

        e.printStackTrace();
    } catch (SAXException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    } catch (JAXBException e) {

        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {

        e.printStackTrace();
    }

}

Issue might be that you are not looping the List . 问题可能是您没有循环List From the below source of yours, you are just taking the first item for comparison. 从下面的来源中,您只是将第一项进行比较。

Person  person  = iter.next();

You need to loop the entire list for comparison. 您需要循环整个列表以进行比较。

@Jayamohan @Jayamohan

I already put a loop like this: but the code only works for update only, not for "Add" element 我已经放了一个这样的循环:但是代码仅适用于更新,不适用于“添加”元素

 for (Iterator<Person> iterator = listPerson .iterator(); iterator.hasNext(); )
 {  
  Person person= iterator.next();
   //this peace of code works for update value
   if(person.getName().equals(name) && !person.getId().equals(id)){ 
    person.setId(id); 
   }else if (!person.getName().equals(name) && person.getId().equals(id)){  
     person.setName(name); 
    } 
  }

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

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