如何在JAXB解组后防止丢失引用的嵌套元素

时间:2015-08-27 11:34:43

标签: xml xsd jaxb unmarshalling jaxb2

我有两个xsd,User.xsd中的元素有来自Roles.xsd的引用,如下所示

User.xsd

    <?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://www.myapp.com/xsd/user"
        elementFormDefault="qualified"
        xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        xmlns:role="http://www.myapp.com/xsd/role"
        xmlns:user="http://www.myapp.com/xsd/user"
        jaxb:version="2.1">
    <annotation><appinfo>
    <jaxb:schemaBindings>
        <jaxb:package name="com.foo.user"/>
    </jaxb:schemaBindings>
    </appinfo></annotation>
<import schemaLocation="Role.xsd" namespace="http://www.myapp.com/xsd/role"/>

<element name="user">
    <complexType>
        <sequence>
            **<element ref="role:roles"/>**
        </sequence>
    </complexType>
</element>

Role.xsd

    <?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://www.myapp.com/xsd/role"
        elementFormDefault="qualified"
        xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        xmlns:role="http://www.myapp.com/xsd/role"
        xmlns:user="http://www.myapp.com/xsd/user"
        jaxb:version="2.1">
    <annotation><appinfo>
    <jaxb:schemaBindings>
        <jaxb:package name="com.foo.role"/>
    </jaxb:schemaBindings>
    </appinfo></annotation>

<element name="roles">
    <complexType>
        <sequence>
            <element name="role" type="role:Role" minOccurs="0"/>
        </sequence>
    </complexType>
</element>

<complexType name="Role">
    <complexContent>
        <extension base="u:Role">
            <attribute name="name" type="string"></attribute>
            <attribute name="action" type="string"></attribute>
        </extension>
    </complexContent>
</complexType>

我正在尝试解组User.xsd并期望正确的结果如下

    <user>
    <name>John</name>
    <roles>
        <role>
            <name>admin</name>
            <action>ALL</action>
        </role>
        <role>
            <name>manager</name>
            <action>ALL</action>
        </role>
    </roles>
</user>

但是我得到的以下输出不包含角色信息

<user>
<name>John</name>
<ns2:enter code hereroles>
    <ns2:role/>
</ns2:roles>

解组

JAXBContext jaxbContext = JAXBContext.newInstance("com.foo.user");
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return (User) unmarshaller.unmarshal(inputStream);

如何使用角色信息解组User对象。

0 个答案:

没有答案