如何使用允许在jibx中使用多个枚举值的属性来解组XML文档



我想使用Jibx来解组以下XML(存储在一个名为test.XML的文件中):

<?xml version="1.0" encoding="UTF-8"?>
<rootElement attrWithEnum="avalue anothervalue" xsi:schemaLocation="my:target:ns simple.xsd" xmlns="my:target:ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</rootElement>

我定义了模式(在一个名为simple.xsd的文件中),如下所示:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="my:target:ns" xmlns="my:target:ns" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">            
<xs:element name="rootElement">
<xs:complexType>
<xs:attribute name="attrWithEnum" use="required">
<xs:simpleType>
<xs:list>
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="avalue"/>
<xs:enumeration value="anothervalue"/>
</xs:restriction>
</xs:simpleType>
</xs:list>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>    
</xs:schema>

使用org.jibx.schema.codegen.CodeGen工具从中生成Java文件,并编写了以下测试程序:

package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import my.target.ns.RootElement;
public final class Program {
public static void main(final String[] args) {                
try {
IBindingFactory bfact = BindingDirectory.getFactory(RootElement.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
FileInputStream in = new FileInputStream(new File("test.xml"));
RootElement data = (RootElement) uctx.unmarshalDocument(in, null);
// This is not what I was expecting. I was expecting 
// List<RootElement.Enumeration> (or equivalent) not
// a single RootElement.Enumeration instance
RootElement.Enumeration attrValue = data.getAttrWithEnum();
System.out.println(attrValue);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}

此程序失败,错误为:

org.jibx.runtime.jibx异常:在枚举类my.target.ns.RootElement$Enumeration 中找不到值"avalue anothervalue"的匹配项

如果我这样调整输入XML(即只设置一个枚举值),它就会工作(打印AVALUE)。

<rootElement attrWithEnum="avalue" xsi:schemaLocation="my:target:ns simple.xsd" xmlns="my:target:ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

因此,jibx似乎不喜欢我允许枚举值的列表(我本来希望getAttrWithEnum返回一个集合,但它返回一个对象——请参阅上面代码示例中的注释)。

当我使用jaxb(使用xjc生成java文件)时,相同的XSD也能很好地工作,所以我认为我的XSD是有效的(尽管如果有更好的方法来定义我想要的,那也没关系)。

因此,我的问题是:

如何使用允许在jibx中使用多个枚举值的属性对XML文档进行解组

我从您的模式中生成了一个带有xjcRootElement类。attrWithEnum属性的字段变为List<String> attrWithEnum,它将把属性中的每个单词划分为列表中的一个单独字符串。这将允许任何字符串值,而不仅仅是枚举中定义的字符串值。

将其更改为仅String attrWithEnum当然会按原样存储属性。

我将类型更改为枚举:

enum AttrEnum {
avalue,
anothervalue
}
@XmlAttribute(name = "attrWithEnum", required = true)
public List<AttrEnum> attrWithEnum;

使用JAXB(我从未使用过Jibx),这给了我一个只有有效值的列表。属性中未在枚举中定义的任何值都将作为null值返回。

如果属性仅包含枚举中的一个有效值,则将字段更改为AttrEnum attrWithEnum只会返回非null值。

所以我猜测RootElement类将attrWithEnum定义为单个enum,而不是枚举列表(List<AttrEnum>)

最新更新