在這小節中,我們將使用基於Java的XSD驗證器來針對students.xsd驗證檔案:students.xml。
檔案:students.xml -
<?xml version = "1.0"?>
<class>
<student rollno = "1010">
<firstname>Dinkar</firstname>
<lastname>King</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "1020">
<firstname>Vaneet</firstname>
<lastname>Su</lastname>
<nickname>Vaneet</nickname>
<marks>95</marks>
</student>
<student rollno = "1030">
<firstname>Jasvir</firstname>
<lastname>Lee</lastname>
<nickname>Jasvir</nickname>
<marks>90</marks>
</student>
</class>
檔案:students.xsd -
<?xml version = "1.0"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = 'class'>
<xs:complexType>
<xs:sequence>
<xs:element name = 'student' type = 'StudentType' minOccurs = '0'
maxOccurs = 'unbounded' />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name = "StudentType">
<xs:sequence>
<xs:element name = "firstname" type = "xs:string"/>
<xs:element name = "lastname" type = "xs:string"/>
<xs:element name = "nickname" type = "xs:string"/>
<xs:element name = "marks" type = "xs:positiveInteger"/>
</xs:sequence>
<xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>
</xs:complexType>
</xs:schema>
檔案:XSDValidator.java -
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class XSDValidator {
public static void main(String[] args) {
if(args.length !=2){
System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" );
} else {
boolean isValid = validateXMLSchema(args[0],args[1]);
if(isValid){
System.out.println(args[1] + " is valid against " + args[0]);
} else {
System.out.println(args[1] + " is not valid against " + args[0]);
}
}
}
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException e){
System.out.println("Exception: "+e.getMessage());
return false;
}catch(SAXException e1){
System.out.println("SAX Exception: "+e1.getMessage());
return false;
}
return true;
}
}
針對XSD驗證XML的步驟
將XSDValidator.java檔案複製到一個工作目錄位置,例如:D:\worksp\xsd,將students.xml 和students.xsd 這兩個檔案複製到相同的工作目錄位置(D:\worksp\xsd)。
開啟命令列控制台編譯XSDValidator.java,確保在計算機上安裝了JDK 1.5以及類路徑。 有關如何使用JAVA的詳細資訊,請參閱JAVA教學。
D:\worksp\xsd>javac XSDValidator.java
執行XSDValidator,並將students.xsd和students.xml這兩個檔案名稱作為引數傳遞。輸出結果如下所示 :
D:\worksp\xsd>java XSDValidator students.xsd students.xml
students.xml is valid against students.xsd