JAXB XMLAdapter 方法不抛出异常 [英] JAXB XMLAdapter method does not throws Exception
问题描述
我正在使用 JAXB XMLadapter 来编组和解组布尔值.C# 应用程序也将访问应用程序的 XML 文件.我们必须验证这个 XML 文件,这是使用 XSD 完成的.C# 应用程序为布尔节点写入True"值.但是我们的 XSD 确实会验证相同的内容,因为它只允许真/假"或1/0".因此,我们在 XSD 中保留了布尔值的字符串,并且该字符串将由 XMLAdapter 验证以在我们这边进行编组和解组.XML 适配器如下:
I am using JAXB XMLadapter to marshal and unmarshal Boolean values. The application's XML file will be accessed by C# application also. We have to validate this XML file and this is done using XSD. C# application writes "True" value for Boolean nodes. But the same does get validated by our XSD as it only allows "true/false" or "1/0". So we have kept String for boolean values in XSD and that string will be validated by XMLAdapter to marshal and unmarshal on our side. The XML Adapter is as follows:
public class BooleanAdapter extends XmlAdapter<String, Boolean> {
@Override
public Boolean unmarshal(String v) throws Exception {
if(v.equalsIgnoreCase("true") || v.equals("1")) {
return true;
} else if(v.equalsIgnoreCase("false") || v.equals("0")) {
return false;
} else {
throw new Exception("Boolean Value from XML File is Wrong.");
}
}
@Override
public String marshal(Boolean v) throws Exception {
return v.toString();
}
}
上面的代码在正常情况下工作,但是当从 xml 文件中读取无效数据(例如:abcd"或")时,throw new Exception();"没有得到传播,解组过程继续读取下一个节点.我希望应用程序在抛出异常时立即停止.看来我的异常被吃掉了.非常感谢任何帮助.
The code above works in normal conditions, but when invalid data(eg: "abcd" or "") is read from xml file then the "throw new Exception();" is not getting propagated and the Unmarshal process moves on to read next node. I want the application to stop as soon as an exception is thrown. It seems my Exception is getting eaten away. Any help is much appreciated.
如何解决这个问题?
推荐答案
来自XMLAdapter#unmarshal(ValueType)
:
抛出:java.lang.Exception
- 如果在转换过程中出现错误.调用者负责通过ValidationEventHandler向用户报告错误.
Throws:
java.lang.Exception
- if there's an error during the conversion. The caller is responsible for reporting the error to the user through ValidationEventHandler.
所以,是的 - 例外是 eaten 然后使用 ValidationEventHandler
,不会被扔到栈顶.
So, yes - the exception is eaten and then reported using ValidationEventHandler
, not thrown to the top of your stack.
检查您是否已经在使用任何(可能是自定义的)ValidationEventHandler
将您的异常分组,或使用 DefaultValidationEventHandler
,像这样:
Check if you are already using any (custom, perhaps) ValidationEventHandler
that groups your exceptions, or use DefaultValidationEventHandler
, like this:
unmarshaller.setEventHandler(new DefaultValidationEventHandler());
它会在第一个错误时导致解组失败.
It will cause unmarshalling failure on first error.
这篇关于JAXB XMLAdapter 方法不抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!