我有一个以下格式的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的形式出现2次,第二次以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)
答案 0 :(得分:1)
使用extension标记创建一个新类型,扩展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"/>
答案 1 :(得分:0)
在@ mascoj的答案的基础上,尝试这个架构:
<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>