如何在Java中使用“ minOccurs”验证xml?

时间:2018-11-12 07:12:17

标签: java xml xsd

我正在使用javax.xml.validation.Validator根据架构验证xml。我有一个要求,其中输入xml包含“ minOccurs”和“ maxOccurs”字段。如果我根据架构对此进行验证,那么我将得到org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 7; cvc-complex-type.3.2.2: Attribute 'minOccurs' is not allowed to appear in element。该如何解决?

验证:

URL url;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
url = classLoader.getResource(schemaLocation);
String xsd = url.toURI().getPath();
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File f = new File(xsd);
schema = factory.newSchema(f);
Validator valid = schema.newValidator();
StringReader xml = new StringReader(request);
valid.validate(new StreamSource(xml));
xml.close();

XSD:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="item">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema> 

XML:

<order>  
  <item>
    <name minoccurs="1" maxOccurs="unbounded">apple</name>   
  </item>
</order> 

2 个答案:

答案 0 :(得分:0)

再次尝试验证您提供的XSD的XML会给您以下错误:

  

属性“ minoccurs”无法显示在元素“ element”中。

XSD指标specification告知发生指标是:

  

maxOccurs

     

minOccurs

带有大写'O'

将您的XSD更改为:

<xs:sequence>
    <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>

您的XML到:

<order>  
  <item>
    <name>apple</name>   
  </item>
</order>

答案 1 :(得分:0)

您不应在XML元素名称中输入minoccurs="1" maxOccurs="unbounded"

您需要的是:

<order>  
  <item>
    <name>apple</name>   
  </item>
</order>

使用当前代码,它正在寻找xsd文件中未定义的属性minoccursmaxOccurs

编辑:

如果您想将minOccursmaxOccurs用作元素name的属性,并保留 <name minOccurs="1" maxOccurs="unbounded">apple</name>,然后您需要像这样在XSD中声明这些属性。

<xs:complexType>
    <xs:sequence>
        <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="minOccurs" type="xs:integer"/>
    <xs:attribute name="maxOccurs" type="xs:integer"/>
</xs:complexType>