我有类似以下 XML 文件的内容。
<credits>
<property name="tag">
<item>v0003</item>
</property>
<property
name="tag">
<item>mhma03h</item>
</property>
</credits>
第一个要求是这个 XML 无论如何都不能改变。请不要在下面建议这样做。
我需要编写一个验证这一点的模式。以及进行验证的 Java 代码。
我完全被卡住了,我真的不知道发生了什么。
像这样的架构是什么样的?我已经得到了一个,但它太糟糕了,我不会打扰发布。:PI 不想将命名空间附加到 XML 元素。他们是一成不变的。^_^
我该如何做到这一点,以便解析器“找到”所有这些元素?我可以告诉它忽略所有这些命名空间的废话。通过这种针对模式进行验证的应用,命名空间冲突是不可能的。
我试过把
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="books" elementFormDefault="unqualified">
对于我的命名空间信息和
更新:我已经更新了我正在做的事情以反映迄今为止给出的答案!:)
XSD
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="property">
<xs:complexType>
<xs:sequence>
<xs:element ref="item"/>
</xs:sequence>
<xs:attribute name="name" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="tag"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="item">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="mhma03h"/>
<xs:enumeration value="v0003"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="credits">
<xs:complexType>
<xs:sequence>
<xs:element ref="property" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML v0003
加载和验证是的代码。在您询问之前,可以加载文件。我已经检查了大约 20 次。:P
SAXParserFactory factory = SAXParserFactory.newInstance();
SchemaFactory schemaFactory =
SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(
new Source[] {new StreamSource("small.xsd")}));
javax.xml.parsers.SAXParser parser = factory.newSAXParser();
org.xml.sax.XMLReader reader = parser.getXMLReader();
reader.setFeature("http://xml.org/sax/features/validation", true);
reader.setFeature("http://apache.org/xml/features/validation/schema", true);
reader.parse(new InputSource("small.xml"));