Java XML Schema validation: prefix not bound

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I have followed this tutorial for validating XML files. But I am receiving exception when validating XML file. What I am doing wrong? My codes:
XML schema:

                                                                                                                                               

XML file to validate:

               FirstName         Lastname         +xxxxxxxxxxxx      

Java source for validating:

import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.*; import org.xml.sax.SAXException; import java.io.*;  public class ProtocolValidator {     public static void main(String [] args) throws Exception     {         Source schemaFile = new StreamSource(new File("schema.xsd"));         Source xmlFile = new StreamSource(new File("test_xml.xml"));          SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);         Schema schema = schemaFactory.newSchema(schemaFile);         Validator validator = schema.newValidator();          try{             validator.validate(xmlFile);             System.out.println(xmlFile.getSystemId() + " is valid");         }         catch (SAXException e)          {             System.out.println(xmlFile.getSystemId() + " is NOT valid");             System.out.println("Reason: " + e.getLocalizedMessage());         }     } }

Exception I am receiving:

Exception in thread "main" org.xml.sax.SAXParseException; systemId: file:/root/test/schema.xsd; lineNumber: 4; columnNumber: 50; The prefix "xs" for element "xs:element" is not bound.     at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)...

回答1:

The XML schema file itself needs to be a valid XML document. You are missing the outer schema element and the namespace declaration for the xs prefix.

      


回答2:

Add this line to your schema, just below the first line:

... and a closing tag as the last line in the schema:

 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!