JAXB XMLAdapter方法不会抛出异常 [英] JAXB XMLAdapter method does not throws Exception
问题描述
我正在使用JAXB XMLadapter来编组和解组布尔值。应用程序的XML文件也将由C#应用程序访问。我们必须验证此XML文件,这是使用XSD完成的。 C#应用程序为布尔节点写入True值。但是我们的XSD也证实了这一点,因为它只允许真/假或1/0。因此,我们在XSD中保留了String的布尔值,并且该字符串将由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();没有传播,Unmarshal进程继续读取下一个节点。
我希望应用程序在抛出异常时立即停止。
看来我的异常被吃光了。
非常感谢任何帮助。
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.
所以,是 - 异常吃掉,然后使用 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屋!