2017-02-04 51 views
0

我想解組與JAXB類不匹配的XML字符串。我期望這會引發異常,但是會返回一個新的JAXB對象。JAXB解組的壞XML不會拋出異常

xmlStr(輸入XML)

<urn1:RgBad 
    xmlns:urn1="urn:none"> 
</urn1:RgBad> 

正確的XML

<urn:Rg 
    xmlns:urn="urn:test" 

代碼

(clazz = Rg.class) 
    JAXBContext jaxbContext = JAXBContext.newInstance(clazz); 
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
    StreamSource source = new StreamSource(new StringReader(xmlStr)); 
    //Returns an actual Rg object, even though the source root element and namespace are different. 
    (unmarshaller.unmarshal(source, clazz)).getValue(); 
+0

您應該在JAXB中添加模式驗證。 –

回答

0

可以使用JAXB

當嘗試添加您的架構來驗證XML文件
try { 
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
    Schema schema = sf.newSchema(new File("yourSchema.xsd")); 
    JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName()); 
    Unmarshaller u = jc.createUnmarshaller(); 
    u.setSchema(schema); 
    u.setEventHandler(ehdler); 

    obj = u.unmarshal(xml); 
} catch (JAXBException e) { 
} finally { 
} 
+0

謝謝。我希望不必進行模式驗證,但我認爲驗證必須全部或全部與JAXB解組。 – user994165