Jing Relaxng长度验证字符串

时间:2014-02-11 15:15:03

标签: java xml relaxng

我正在使用Jing API进行RelaxNG和xml验证。 我无法验证我指定的字符串的长度。 我在java中编写了以下独立代码。 在relaxng文件中,我指定minLength验证为3,在代码中我传递空字符串仍然jing api没有抛出任何错误。字符串的验证不是happing。我正在使用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>

1 个答案:

答案 0 :(得分:2)

你需要像这样指定你的参数:

<rng:param name="minLength">3</rng:param>

你拥有它的方式,你有<param>,它不在Relax NG名称空间中,因此被忽略了。此外,您有minlength但参数名称为minLength且大写为“L”。