私は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'.
私の質問は、なぜルートがスキーマの名前空間になければならないのかということです。それは私がxmlドキュメントを正しく検証していないということでしょうか?
public synchronized boolean isValid(String xmlFragment、File xmlSchema)throws SAXException、IOException {
// 1.W3CXMLスキーマ言語のファクトリを検索します
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; }