我有一个xml,格式如下:
<data>
<index id="Name">Mesut</index>
<index id="Age">28</index>
</data>
现在这个xml的元素是相同的,即索引。由此生成的XSD如下:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="data">
<xs:complexType>
<xs:sequence>
<xs:element name="index" maxOccurs="unbounded" type="xs:string">
<xs:complexType>
<xs:attribute name="id" type="xs:string"></xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
上面xsd的问题是,这个xsd无法验证一个与索引具有相同标记的xml,该标记出现了两次,一次是String,第二次是Integer。因为xsd只能验证字符串。
现在我用来验证的代码如下:
public static void main(String[] args){
boolean b = true;
File fXml = new File("C:\Users\Mesut\Desktop\XMLAndXSD\MainXml.xml");
File fXsd = new File("C:\Users\Mesut\Desktop\XMLAndXSD\MainXml.xsd");
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = schemaFactory.newSchema(fXsd);
schema.newValidator().validate(new StreamSource(fXml));
} catch(SAXException sax) {
System.out.println("exception in sax");
b = false;
sax.printStackTrace();
} catch(IOException io) {
System.out.println("exception in io");
b = false;
io.printStackTrace();
}
System.out.println(b);}
运行上述代码时的异常如下:
enter code hereorg.xml.sax.SAXParseException; systemId: file:/C:/Users/Vikas/Desktop/XMLAndXSD/MainXml.xsd; lineNumber: 6; columnNumber: 93; src-element.3: Element 'index' has both a 'type' attribute and a 'anonymous type' child. Only one of these is allowed for an element.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
使用扩展标记创建一个新类型,该类型扩展xs:string以包括属性id。在模式的开头位置:
<xs:complexType name="indexType">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="id" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
然后在"数据"中执行:
<xs:element name="index" maxOccurs="unbounded" type="indexType"/>
基于@maskoj的答案,尝试以下模式:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://myns">
<xs:element name="data">
<xs:complexType>
<xs:sequence>
<xs:element name="index" maxOccurs="unbounded" minOccurs="0">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute type="xs:string" name="id" use="optional"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
验证以下xml实例:
<f:data xmlns:f="http://myns">
<f:index id="Name">Mesut</f:index>
<f:index id="Age">28</f:index>
</f:data>