源码

java-无法针对xsd验证xml


我是学习XSD的新手.我编写了一个XSD文件和XML文件,以及一个程序来针对XSD验证XML.当我运行程序时,出现错误消息,指出从元素“ id”开始发现无效内容.预期为“ {id}”之一.有人可以解释我要去哪里了.

XSD文件:


    
        
            
                
                    
                    
                    
                    
                
            
        

和XML文件:


    

       1234
       Pradeep
       Sanskrit
       Beginner
    

验证XML文件的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 ValidatorDemo {

    public static void main(String[] args) {

      System.out.println("student.xml validates against studentRule.xsd? "+validateXMLSchema("studentRule.xsd", "student.xml"));

      }

    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 | SAXException e) {
            System.out.println("Exception: "+e.getMessage());
            return false;
        }
        return true;
    }
}
(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/java-wufazhenduixsdyanzhengxml.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:11月 12, 2019 at 10:01 上午

热评文章