这与这个问题和这个问题我昨天问。
我想使用布尔值来确定 XML 文档中是否存在某个元素。我正在解析的文件允许使用如下元素:
<FamilyMember>
<Name>Jeff</Name>
</FamilyMember>
<FamilyMember>
<Name>Spot</Name>
<IsPet/>
</FamilyMember>
在此示例中,该元素指定 FamilyMember 是宠物,但没有与该元素关联的其他数据。我希望能够告诉 JAXB 根据解析文件中是否存在该元素返回一个布尔值。如果该元素存在,则该值应该为 true;否则,它应该是假的。如果可能的话,我想从我用来生成 Java 类的 XSD 模式中实现这一点。
This is somewhat related to this question and this question which I asked yesterday.
I would like to use a boolean to determine whether or not an element exists in an XML document. The files that I am parsing allow for elements such as the following:
<FamilyMember>
<Name>Jeff</Name>
</FamilyMember>
<FamilyMember>
<Name>Spot</Name>
<IsPet/>
</FamilyMember>
In this example, the element specifies that the FamilyMember is a pet, but there is no additional data associated with this element. I would like to be able tell JAXB to return a boolean based on whether or not the element exists in the parsed file. If the element exists, the value should be true; otherwise, it should be false. I would like to to this from within the XSD schema which I use to generate my Java classes, if possible.
发布评论
评论(2)
您应该能够使用类似于以下内容的 XmlAdapter 来执行此操作:
一旦你得到了答案(如何指定适配器)哪个 JAXB 用于封送/解封数据?)您将能够应用该适配器。
以下是如何做到这一点。请注意,以下示例使用 EclipseLink JAXB (MOXy) 运行,但在以下情况下抛出异常:使用 JAXB 参考实现。
FamilyMember
IsPetAdapter
演示
You should be able to do this with an XmlAdapter similar to the following:
Once you have the answer to ( How do I specify the adapter(s) which JAXB uses for marshaling/unmarshaling data?) you will be able to apply the adapter.
The following is how it could be done. Note the following example works using EclipseLink JAXB (MOXy), but throws an exception when the JAXB reference implementation is used.
FamilyMember
IsPetAdapter
Demo
您的 IsPet 是否表现为布尔值?在这种情况下,我猜测如果 XML 中不存在布尔值,则该布尔值将为 null。我认为这个问题表明情况确实如此。
Does your IsPet manifest as a Boolean? In which I case I'd guess that the Boolean would be null if it's not present in the XML. I think this questionindicates this is the case.