JAXB 2.0验证无效

时间:2010-12-09 14:59:21

标签: java xml validation jaxb jaxb2

我正在研究JAXB 2.0,并且由于其无法按预期工作,因此目前正在验证部分。 下面是验证码

public void validateXMLToSchema(Unmarshaller ummarshaller,String xsdFileName) throws SAXException, JAXBException{
    System.out.println(getClass().getResource(DEFAULT_XSD_NAME).toString());
    Schema schema;
    SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    if(null==xsdFileName)
        schema=schemaFactory.newSchema(getClass().getResource(DEFAULT_XSD_NAME));

    else
        schema=schemaFactory.newSchema(new File(xsdFileName));

    ummarshaller.setSchema(schema);
    ummarshaller.setEventHandler( new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent validationevent) {
            if(validationevent.getSeverity()==ValidationEvent.FATAL_ERROR || validationevent.getSeverity()==ValidationEvent.ERROR || validationevent.getSeverity()==ValidationEvent.WARNING){
                ValidationEventLocator  locator = validationevent.getLocator();
                log.info("Line:Col[" + locator.getLineNumber()
                        + ":" + locator.getColumnNumber()
                        + "]:" + validationevent.getMessage());
            }
            return true;
        }
    });

}

这是对方法的调用

Destination destination=new Destination();
    try {
         destination=(Destination)unmarshal(Destination.class,new FileInputStream(new File("C:/Users/Raisonne/Desktop/jaxb/jaxb-ri-20101119/bin/destination.xml")));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    System.out.println(destination.getName());

}

public static <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException, SAXException {
String packageName = docClass.getPackage().getName();
JAXBContext jc = JAXBContext.newInstance( packageName );
Unmarshaller u = jc.createUnmarshaller();
XMLValidator xmlValidator=new XMLValidator();
xmlValidator.validateXMLToSchema(u, null);

我有几个字段作为XSD的必填字段,但即使删除它shd给我错误,而它没有给出任何东西并解析我的xml文件到相应的对象 任何一点都可能出错?

这是XSD的一部分

    <xs:element name="destination" type="Destination"/>
  <xs:complexType name="Destination">
    <xs:sequence>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="destinationID" type="xs:string" minOccurs="0"/>
      <xs:element name="shortDescription" type="xs:string" minOccurs="0"/>
      <xs:element name="longDescription" type="xs:string" minOccurs="0"/>
      <xs:element name="stateID" type="xs:string"/>
      <xs:element name="typeCode" type="xs:int"/>
      <xs:element name="countryCode" type="xs:string"/>
      <xs:element name="categories" type="xs:string"/>
      <xs:element name="transport" type="Transport" minOccurs="0" maxOccurs="1"/>
      <xs:element name="culture" type="Culture" minOccurs="0" maxOccurs="1"/>
      <xs:element name="events" type="Events" minOccurs="0" maxOccurs="1"/>
      <xs:element name="placesToVisit" type="PlacesToVisit" minOccurs="0" maxOccurs="1"/>
      <xs:element name="contacts" type="Contact" minOccurs="0" maxOccurs="1"/>
      <xs:element name="addresses" type="address" minOccurs="0" maxOccurs="1"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

生成Java文件

@XmlElement(required = true)
protected String name;
protected String destinationID;
protected String shortDescription;
protected String longDescription;
@XmlElement(required = true)
protected String stateID;

我正在从xml文件中删除stateID,但在验证部分

中仍然没有警报

提前致谢

3 个答案:

答案 0 :(得分:1)

您的代码片段有点难以理解,实际上是一个解组吗?您可能需要将最后一行添加到unmarshal方法中:

public static <T> T unmarshal( Class<T> docClass, InputStream inputStream ) throws JAXBException, SAXException {
    String packageName = docClass.getPackage().getName();
    JAXBContext jc = JAXBContext.newInstance( packageName );
    Unmarshaller u = jc.createUnmarshaller();
    XMLValidator xmlValidator=new XMLValidator();
    xmlValidator.validateXMLToSchema(u, null);
    u.unmarshal(inputStream);
}

答案 1 :(得分:0)

根据这条线

xmlValidator.validateXMLToSchema(u, null);

您没有将XSD文件名提供给XmlValidator。它应该像

xmlValidator.validateXMLToSchema(u, "/opt/projects/myschema.xsd");

编辑:这就是我设法做到这一点并且它完美运作的方式:

void validate(MyRequest requestParameters) throws IllegalArgumentException,MalformedURLException,SAXException {
    try {
        JAXBContext context = JAXBContext.newInstance(MyRequest.class.getPackage().getName());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setSchema(getSchema());
        JAXBElement<MyRequest> rootElement = new JAXBElement<SearchCustomersRequest>(new QName("http://mysite.com/xsd/myproject/", "MyRequest"),
                        MyRequest.class, requestParameters);
        marshaller.marshal(rootElement, new DefaultHandler());
        log.debug("Validation successful");
    } catch (JAXBException e) {
        throw new IllegalArgumentException("Invalid request parameters: " + e.toString(), e);
    }
}

private Schema getSchema() throws MalformedURLException, SAXException {
    if (schema == null) {
        SchemaFactory factory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = new URL("http://mysite.com/xsd/myproject/schema-1.0.xsd");
        schema = factory.newSchema(schemaUrl);
    }
    return schema;
}

答案 2 :(得分:0)

当我将代码更改为此

时,真的很奇怪
public class UnMarshallXML {

/**
 * @param args
 * @throws SAXException 
 */
public static void main(String[] args) throws SAXException {
    Destination destination=new Destination();
    try {
         destination=(Destination)unmarshal(Destination.class,new FileInputStream(new File("C:/Users/Raisonne/Desktop/jaxb/jaxb-ri-20101119/bin/destination.xml")));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    System.out.println(destination.getName());

}

public static <T> T unmarshal( Class<T> docClass, InputStream inputStream )
throws JAXBException, SAXException {
String packageName = docClass.getPackage().getName();
System.out.println(packageName);
JAXBContext jc = JAXBContext.newInstance( packageName );
Unmarshaller u = jc.createUnmarshaller();
SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema=schemaFactory.newSchema(new File("C:/Users/Raisonne/Desktop/jaxb/jaxb-ri-20101119/bin/destination.xsd"));

u.setSchema(schema);
u.setEventHandler(
        new ValidationEventHandler() {
            // allow unmarshalling to continue even if there are errors
            public boolean handleEvent(ValidationEvent ve) {
                // ignore warnings
                if (ve.getSeverity() != ValidationEvent.WARNING) {
                    ValidationEventLocator vel = ve.getLocator();
                    System.out.println(
                            "Line:Col[" + vel.getLineNumber()
                            + ":" + vel.getColumnNumber()
                            + "]:" + ve.getMessage());
                }

                return true;
            }
        });
// XMLValidator xmlValidator=new XMLValidator();
//xmlValidator.validateXMLToSchema(u, null,inputStream);
@SuppressWarnings("unchecked")
JAXBElement<T> doc = (JAXBElement<T>)u.unmarshal( inputStream );
return doc.getValue();

}

}

一切都像魅力一样开始......