2014-10-03 62 views
2

如果XML文件正確解組,JAXB可以說它是有效的嗎? (因爲我們正確地獲得POJO對象)通過JAXB驗證XML

+0

你讓我們知道如果多數民衆贊成正常工作。 :) – Xstian 2014-10-03 15:13:48

回答

2

如果解組正常工作的XML是結構良好的,但如果你有一個模式,你可以添加一個XSD驗證。

下面是一個Schema Validation的例子。

JAXBContext jaxbContext = JAXBContext.newInstance(new Class[]{Root.class}); 
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 

    //Source yourSchema.xsd 
    InputStream xsdStream = CopyMetaInfos.class.getClassLoader().getResourceAsStream(SCHEMA); 
    StreamSource xsdSource = new StreamSource(xsdStream); 

    Schema schema = schemaFactory.newSchema(new StreamSource[]{xsdSource}); 

    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
    unmarshaller.setSchema(schema); 
    Root root = (Root) unmarshaller.unmarshal(is); 

如果XML遵循模式約束,則此驗證將檢查。

e.g(這個元素必須是0 < = X < = 10)

<xs:element name="age"> 
    <xs:simpleType> 
    <xs:restriction base="xs:integer"> 
     <xs:minInclusive value="0"/> 
     <xs:maxInclusive value="100"/> 
    </xs:restriction> 
    </xs:simpleType> 
</xs:element> 

e.g(這個元素必須強制)

<xs:element name="child_name" type="xs:string" minOccurs="1"/> 
+0

謝謝。所需要的只是一個格式良好的XML,但是根據我的項目需求,它是一個加號來驗證它。 – 2014-10-05 07:31:43

1

在XML有效性(格式良好等)的意義上有效 - 是的。

從一定程度上符合某些XML Schema的有效性 - no。即使你使用XJC從這個模式中生成了你的類,答案是沒有。即使JAXB解組沒有錯誤,Int也可能在該模式中無效。

如果你想確保你的XML符合你的XML模式,你必須明確地驗證它。這裏有一個相關的問題:

Validating against a Schema with JAXB

+0

很好的答案。解決了我的疑問。 – 2014-10-05 07:33:13