在解组XML文件时获取ClassCastException(JAXBContext传递正确的类名)

时间:2014-09-23 13:28:47

标签: java xml jaxb

我有一个调用此方法的代码。解组时我得到一个ClassCastException。我在创建JAXBContext对象时传递了正确的类名。

public TestsuiteType parseTestSuiteXML(String path) throws JAXBException, FileNotFoundException {
        JAXBContext context = JAXBContext.newInstance(TestsuiteType.class);
        Unmarshaller um = context.createUnmarshaller();
        TestsuiteType ts = (TestsuiteType) um.unmarshal(new FileReader("/Users/admin/Documents/workspace_Nishant_dev/Practice/xmls/TEST-junit.xml"));
        List<TestcaseType> tcs = ts.getTestcase();
        Iterator<TestcaseType> it = tcs.iterator();
        while(it.hasNext()) {
            TestcaseType tc = it.next();
            if(tc.getContent().size() == 0) {
                tcs.remove(tc);
            }
        }
        return ts;
    }

上述代码的异常跟踪:

Exception in thread "main" java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to com.jaxb.testjunit.TestsuiteType
    at com.jaxb.testing.FailureProcessor.parseTestSuiteXML(FailureProcessor.java:49)
    at com.jaxb.testing.FailureProcessor.main(FailureProcessor.java:24)

1 个答案:

答案 0 :(得分:2)

您获得的是JAXBElement<TestSuiteType>,而不是TestSuiteType。您的值在jaxbElement.getValue()