开发者

Validating XML that is a DOM document

开发者 https://www.devze.com 2023-04-06 22:42 出处:网络
How do I validate an XML document that I开发者_JS百科 already have in memory as a DOM Document?You can use the javax.xml.validation APIs to validate XML in memory.Below is an example of using these AP

How do I validate an XML document that I开发者_JS百科 already have in memory as a DOM Document?


You can use the javax.xml.validation APIs to validate XML in memory. Below is an example of using these APIs with a JAXBSource, to validate a DOM model simply use a DOMSource.

package blog.validation;

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.util.JAXBSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

public class Demo {

    public static void main(String[] args) throws Exception {
        Customer customer = new Customer();
        customer.setName("Jane Doe");
        customer.getPhoneNumbers().add(new PhoneNumber());
        customer.getPhoneNumbers().add(new PhoneNumber());
        customer.getPhoneNumbers().add(new PhoneNumber());

        JAXBContext jc = JAXBContext.newInstance(Customer.class);
        JAXBSource source = new JAXBSource(jc, customer);

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File("customer.xsd"));

        Validator validator = schema.newValidator();
        validator.setErrorHandler(new MyErrorHandler());
        validator.validate(source);
    }

}

For More Information

  • http://blog.bdoughan.com/2010/11/validate-jaxb-object-model-with-xml.html


How do you made up your model? I have a solution at work where i get an XML message in text format which i parse using xmlbeans. Then i have the ability to call a validate method on it. So there is a Java class compiled during my maven build which reflects the XSD i have.


There's nothing special about it. The javax.xml.validation validators take a Source. Check the constructors of the implementing classes of Source.

0

精彩评论

暂无评论...
验证码 换一张
取 消