我有一个 xml 文档:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Child name="MyType" compareMode="EQ"></Child>
</Root>
我想在以下 xsd 的帮助下验证这个 xml:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Root">
<xs:complexType>
<xs:sequence>
<xs:element name="Child">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="compareMode" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
当我尝试验证它时,我收到以下错误:
Exception in thread "main" org.xml.sax.SAXException: Validation failed against correct.xml. ErrorMessage:s4s-elt-schema-ns: The namespace of element 'Root' must be from the schema namespace, 'http://www.w3.org/2001/XMLSchema'.
我的问题是为什么Root必须在模式的名称空间中?会不会是我验证 xml 文档不正确?
public synchronized boolean isValid(String xmlFragment, File xmlSchema) throws SAXException, IOException{
// 1. 查找 W3C XML Schema 语言的工厂
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); // 2. Compile the schema. Schema schema = factory.newSchema(xmlSchema); // 3. Get a validator from the schema. Validator validator = schema.newValidator(); // 4. Parse the document you want to check. Source source = new StreamSource(new ByteArrayInputStream(xmlFragment.getBytes())); // 5. Check the document validator.validate(source); return true; }