Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - Validate XSD with XML

I want to know how to validate XML with XSD . XML is not of an element type but a complex type . Since validator class's validate method compare only element type.

So basically I want to valide XSD's complex type with an XML.

e.g.

Basic XSD below

xs:element name="Customer">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="Dob" type="xs:date" />
      <xs:element name="Address">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Line1" type="xs:string" />
            <xs:element name="Line2" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

We can assume we have multiple complex type in the Customer element.

MY XML is

<Address> 
    <Line1>34 thingy street, someplace</Line1> 
    <Line2>sometown, w1w8uu </Line2>
</Address>

How I validate my XML with XSD. Kindly post your suggestions in java

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like

import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

//  .....


    try {
        File xmlFile // read XML file

        File xsdFile // read XSD file

        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(xsdFile);
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlFile));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...