[英]JAXB: Bind element type xs:string to an Enum
我的供应商为我提供了一个XSD
,它的元素定义为String
。 但是在他的说明中,他指出此字符串只能具有3个值中的1个:
例如:
<xs:complexType name="MitigationStatus">
<xs:annotation>
<xs:documentation>
This represents a list of mitigation statuses. Can be OPEN, CLOSED, INVALID
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="status" minOccurs="0" maxOccurs="unbounded" type="xs:string"/>
</xs:sequence>
</xs:complexType>
我想在绑定文件中添加一些内容,以便在解组XML
,状态不是String
而是Enum
。
我发现的所有文档似乎都表明XSD
要求String
为enum
类型。
即使XSD
不是enum
有没有办法将字符串绑定到Enum
类型?
您可以在XML模式中定义此限制,并通过以下指示的更改对其进行稍微修改,然后从中生成Java类。
<xs:simpleType name="StatusType">
<xs:restriction base="xs:string">
<xs:enumeration value="OPEN"/>
<xs:enumeration value="CLOSED"/>
<xs:enumeration value="INVALID"/>
</xs:restriction>
</xs:simpleType>
...
<xs:element name="status" minOccurs="0" maxOccurs="unbounded" type="StatusType"/>
...
这将导致枚举类StatusType。 在XML中,无论如何一切都是字符串,因此它保持原样。
如果您确实想通过绑定文件来执行此操作,则可以使用以下内容:
<jaxb:bindings node="//xsd:complexType[@name='MitigationStatus']">
<jaxb:bindings node="./xsd:element[@name='status']">
<jaxb:property>
<jaxb:baseType>
<jaxb:javaType name="StatusImpl"
parseMethod="StatusImpl.parseStringToEnum"
printMethod="StatusImpl.printEnumToString"/>
</jaxb:baseType>
</jaxb:property>
</jaxb:bindings>
</jaxb:bindings>
假设一个枚举StatusType,类StatusImpl就是
public class StatusImpl {
public static StatusType parseStringToEnum( String value ){
return StatusType.valueOf( value );
}
public static String printEnumToString( StatusType impl ){
return impl.toString();
}
}
我不知道您遇到什么问题,但是以下方法可以正常工作。 如您所见,没有XSD,只有手动编码的JAXB类。
public class Test {
public static void main(String[] args) throws Exception {
String xml = "<Path>\r\n" +
" <Direction>North</Direction>\r\n" +
" <Direction>North</Direction>\r\n" +
" <Direction>East</Direction>\r\n" +
" <Direction>South</Direction>\r\n" +
"</Path>";
JAXBContext jaxbContext = JAXBContext.newInstance(Path.class);
Path path = (Path)jaxbContext.createUnmarshaller().unmarshal(new StringReader(xml));
for (Direction dir : path.directions)
System.out.println(dir);
}
}
@XmlEnum
enum Direction {
@XmlEnumValue("North") NORTH,
@XmlEnumValue("South") SOUTH,
@XmlEnumValue("East") EAST,
@XmlEnumValue("West") WEST
}
@XmlRootElement(name = "Path")
class Path {
@XmlElement(name = "Direction")
List<Direction> directions = new ArrayList<>();
}
输出量
NORTH
NORTH
EAST
SOUTH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.