我无法通过代码使用XSD验证XML。我无法弄清楚我错过了什么 XML:
<?xml version="1.0" encoding="UTF-8"?>
<systems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="test.namespace">
<system address="test" id="test" name="test" systemNr="test">
<mandant mandant="test"/>
</system>
<system address="test2" name="test2" systemNr="test2" id="test2">
<mandant mandant="test2"/>
<mandant mandant="test2"/>
</system>
<system id="test3" address="test3" name="test3" systemNr="test3">
<mandant mandant="test"/>
</system>
</systems>
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test.namespace">
<xs:element name="systems">
<xs:complexType>
<xs:sequence>
<xs:element name="system" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="mandant"
maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:attribute name="mandant"
type="xs:string" use="required">
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required">
</xs:attribute>
<xs:attribute name="name" type="xs:string" use="required">
</xs:attribute>
<xs:attribute name="address" type="xs:string" use="required">
</xs:attribute>
<xs:attribute name="systemNr"
type="xs:string" use="required">
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
以下是代码段:
File systemsFile = new File(LocalFileSystemManager.getDefaultPath() + "Systems.xml");
File schemaFile = new File(LocalFileSystemManager.getDefaultPath() + "SystemsSchema.xsd");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document systemsDocument = db.parse(systemsFile);
systemsDocument.getDocumentElement().normalize();
SchemaFactory factory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(systemsDocument));
提前致谢! 洛瑞
答案 0 :(得分:1)
此实例应验证。您的属性属于架构,因此您需要使用命名空间标记它们:
<?xml version="1.0" encoding="UTF-8"?>
<systems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="test.namespace">
<system a:address="test" a:id="test" a:name="test" a:systemNr="test" xmlns:a="test.namespace">
<mandant a:mandant="test"/>
</system>
...
</systems>
我假设您的attributeFormDefault="qualified"
元素中有elementFormDefault="qualified"
和<schema />
?