我正在使用 Jing API 进行 RelaxNG 和 xml 验证。我无法验证我指定松弛的字符串的长度。我已经用 java 编写了以下独立代码。在松弛文件中,我将 minLength 验证指定为 3,在代码中我传递空字符串仍然 jing api 没有抛出任何错误。字符串的验证没有发生。我正在使用 Jing API。
我的代码:
public static void main(String[] args) throws JAXBException, IOException, SAXException, IncorrectSchemaException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError {
OBJ006 obj006 = new OBJ006();
obj006.setMyInput("");
JAXBContext jc = JAXBContext.newInstance(OBJ006.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
JAXBElement<OBJ006> rootElement =
new JAXBElement<OBJ006>(new QName("obj006"),
OBJ006.class,
obj006);
StringWriter xmlFile = new StringWriter();
marshaller.marshal(rootElement, xmlFile);
String encodedxml = new String(xmlFile.toString().getBytes());
System.out.println(encodedxml);
//Get Schema
File file = new File("C:/XML/Cardinalities/myRelaxNG.xml");
FileInputStream fileInput = new FileInputStream(file);
InputSource schemaSource = new InputSource(fileInput);
SchemaReader schemaReader = new AutoSchemaReader();
Schema schema = schemaReader.createSchema(schemaSource, PropertyMap.EMPTY);
ErrorHandler errorHandler = new ErrorHandlerImpl();
PropertyMapBuilder builder = new PropertyMapBuilder();
builder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
Validator validator = schema.createValidator(builder.toPropertyMap());
TransformerFactory.newInstance().newTransformer()
.transform(new StreamSource(new ByteArrayInputStream(encodedxml.getBytes())),
new SAXResult(validator.getContentHandler()));
}
2.MyRelaxNG.xml
<?xml version="1.0"?>
<!-- Converted to RelaxNG using http://debeissat.nicolas.free.fr/XSDtoRNG.php -->
<rng:grammar xmlns:rng="http://relaxng.org/ns/structure/1.0"
ns="" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
<rng:start combine="choice">
<rng:ref name="obj006" />
</rng:start>
<rng:define name="obj006">
<rng:element name="obj006">
<rng:ref name="obj006ref" />
</rng:element>
</rng:define>
<rng:define name="obj006ref">
<rng:element name="myInput">
<rng:data type="string">
<param name="minlength">3</param>
</rng:data>
</rng:element>
</rng:define>
</rng:grammar>
3.)我的程序的输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<obj006>
<myInput></myInput>
</obj006>