简体   繁体   中英

Binding XML with JAXB annotations

I have the following XML format:

 <repositories>
     <set>
       <id>1</id>
       <name>First</name>
       <spec>data</spec>
     </set>
    <set>
       <id>2</id>
       <name>INFO</name>
       <spec>main</spec>
    </set>
      .
      .
 </repositories>

I create the following package-info.java

 @javax.xml.bind.annotation.XmlSchema (
 elementFormDefault=XmlNsForm.QUALIFIED,
 xmlns = {}
 )

package website.model;

import javax.xml.bind.annotation.XmlNsForm;

ANd the following classes:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Repositories {

@XmlElement
private ListofRepositories repositories;

public ListofRepositories getRepositories() {
    return repositories;
}

public void setRepositories(ListofRepositories repositories) {
    this.repositories = repositories;
}

}

Wrap the sets

@XmlAccessorType(XmlAccessType.FIELD)
public class ListofRepositories {

private List<Sets> set;

public List<Sets> getSet() {
    return set;
}

public void setSet(List<Sets> set) {
    this.set = set;
}

}

And the data:

@XmlAccessorType(XmlAccessType.FIELD)
public class Sets {

private Long id;
private String name;
private String spec;

//get set

}

I don't know why this doesn't work. The response is always null. I implemented similar processes with Java and JAXB annotations and i never had this kind of problem. Does anyone knows what is wrong and how can i fix it?

For the above xml, you need following class structure:

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

@XmlElement
private List<Sets> set;

//getter and setter

}

@XmlAccessorType(XmlAccessType.FIELD)
public class Sets {

private Long id;
private String name;
private String spec;

//getter and setter

}

But, according to your class structure you will get following xml:

<Repositories>
  <repositories>
    <set>
      <id></id>
      <name></name>
      <spec></spec>
    </set>
    <set>
      <id></id>
      <name></name>
      <spec></spec>
    </set>
    .
    .
    .
  </repositories>
</Repositories>

与JAXB你也可以生成从XSD文件这些类-并检查传入的XML对XSD(这将显示为什么它不会接受它)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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