2014-10-03 64 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