不生成@XMLRootElement jaxb

Sit*_*ila 6 java xml xsd jaxb

这是我的.xsd文件

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person" type="PersonType"/>
    <xs:complexType name="PersonType">

        <xs:sequence>
            <xs:element name="Name" type="xs:string"/>
            <xs:element name="Address" type="AddressType" minOccurs="1" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="AddressType">

        <xs:sequence>
            <xs:element name="Number" type="xs:unsignedInt"/>
            <xs:element name="Street" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
Run Code Online (Sandbox Code Playgroud)

使用这个XSD文件我生成了这个类:

package demo5;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PersonType", propOrder = {
  "name",
  "address"
})
public class PersonType {

@XmlElement(name = "Name", required = true)
protected String name;
@XmlElement(name = "Address", required = true)
protected List<AddressType> address;

public String getName() {
    return name;
}

public void setName(String value) {
    this.name = value;
}
public List<AddressType> getAddress() {
    if (address == null) {
        address = new ArrayList<AddressType>();
    }
    return this.address;
}

}
Run Code Online (Sandbox Code Playgroud)

但是XSD文件不会在java文件中生成@XMLRootElement.任何人都可以为此提供解决方案.我知道可以生成根元素,但这不起作用.

bdo*_*han 6

对于对应于命名为复杂类型的全局元素的@XmlElementDecl关于该注解ObjectFactory类将被产生,而不是@XmlRootElement在类注释.这是因为可能存在多个对应于相同命名复杂类型的全局元素.使用此功能无法满足@XmlRootElement.

@XmlRegistry
public class ObjectFactory {

    @XmlElementDecl(name="Person")
    public JAXBElement<PersonType> createPerson(PersonType personType) {
        return new JAXBElement<PersonType>(new QName("Person"), PersonType.class, personType);
    }

}
Run Code Online (Sandbox Code Playgroud)

创造 JAXBContext

JAXBContext基于从XML模式生成的模型创建基础时,应该在生成的模型的包名称上完成.这样就ObjectFactory可以处理类中的元数据.

JAXBContext jc = JAXBContext.newInstance("demo5");
Run Code Online (Sandbox Code Playgroud)

或者生成的ObjectFactory类:

JAXBContext jc = JAXBContext.newInstance(demo5.ObjectFactory.class);
Run Code Online (Sandbox Code Playgroud)

解组班级

当您解组其中根元素对应于@XmlElementDecl注释的类时,您将获得一个JAXBElement返回的实例.

JAXBElement<PersonType> je = (JAXBElement<PersonType>) unmarshaller.unmarshal(xml);
PersonType pt = je.getValue();
Run Code Online (Sandbox Code Playgroud)

如果你想要防止JAXBElement返回,你可以随时使用JAXBIntrospectorunmarshal操作的结果:

PersonType pt = (PersonType) JAXBIntrospector.getValue(unmarshaller.unmarshal(xml));
Run Code Online (Sandbox Code Playgroud)

欲获得更多信息


Puc*_*uce 2

只会@XMLRootElement为顶级元素的匿名类型生成,而不是顶级类型。