0

我有以下示例 xsd

 <annotation><appinfo>
<jaxb:schemaBindings>
    <jaxb:package name="com.myapp"/>
</jaxb:schemaBindings>
</appinfo></annotation>
<element name="user">
    <complexType>
        <sequence>
            <element name="roles" type="u:Roles" minOccurs="1"></element>
        </sequence>
        <attribute name="name" type="string"></attribute>
    </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>

我只想解组一个 Roles xml,如下所示

        JAXBContext c = JAXBContext.newInstance(User.class, Roles.class, Role.class);
    Unmarshaller unmarshaller = c.createUnmarshaller();
    JAXBElement ele = (JAXBElement) unmarshaller.unmarshal(inputStream);
    return (Roles) ele.getValue();

我的输入流/xml 是

<roles>
    <role name="admin" action="all"/>
    <role name="recep" action="select"/>
</roles>

上面的代码抛出以下错误

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.myapp.com/xsd/internal/myapp", local:"roles"). Expected elements are <{http://www.myapp.com/xsd/internal/myapp}User>

如何让我的角色 xml 解组?

4

1 回答 1

1

如果您知道要解组的类,请使用unmarshal(Source source, Class<T> declaredType)and likes。

所以试试unmarshaller.unmarshall(source, Roles.class)哪个会给你JAXBElement<Roles>。然后,您可以getValue()从中获取Roles.

如果您提供用于解组的类,则根元素名称根本无关紧要,JAXB 不需要“知道”它。

于 2015-08-21T13:29:50.500 回答