我是新来学习XSD
。我编写了一个XSD文件和一个XML文件以及一个用于验证XML与XSD的程序。当我运行该程序时,出现错误信息Invalid content was found starting with element 'id'. One of '{id}' is expected
。有人可以解释我哪里出错了。无法验证xml针对xsd
XSD文件:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.edureka.co/Student"
xmlns:st="http://www.edureka.co/Student"
>
<xs:element name="student" type="st:student"></xs:element>
<xs:complexType name="student">
<xs:sequence>
<xs:element name="id" type="xs:int"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="language" type="xs:string"/>
<xs:element name="expertise" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
和XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<student xmlns="http://www.edureka.co/Student"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.edureka.co/Student studentRule.xsd"
>
<id>1234</id>
<name>Pradeep</name>
<language>Sanskrit</language>
<expertise>Beginner</expertise>
</student>
的Java程序来验证XML文件:
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;
}
}
感谢您的回应哪些工作。如果我使用'unqualified',我的xml文档将如何显示。 – zilcuanu
您的原始文档采用“合格”格式,答案中的文档采用“不合格”格式(请注意全局元素“student”中使用的前缀,缺少本地元素的前缀以及缺省缺省值命名空间)。我已经用一些进一步的解释更新了答案。 – teppic