开发者

javax.xml.parsers.DocumentBuilder support for complex types

开发者 https://www.devze.com 2023-01-19 16:58 出处:网络
I\'m trying to put together some validation code.I am trying to validate against a schema like: <?xml version=\"1.0\" encoding=\"UTF-8\"?>

I'm trying to put together some validation code. I am trying to validate against a schema like:

<?xml version="1.0" encoding="UTF-8"?>
<xs开发者_如何转开发d:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xmlns:choice="http://example.com/SimpleChoice" targetNamespace="http://example.com/SimpleChoice" ecore:nsPrefix="choice" ecore:package="com.example.simple.choice">
    <xsd:complexType name="Plane">
        <xsd:sequence>
            <xsd:element name="freightDetails" type="xsd:string" minOccurs="0"/>
            <xsd:element name="passengers" type="xsd:int" minOccurs="0"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

With the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<choice:Plane xmlns:choice="http://example.com/SimpleChoice">
    <freightDetails>Boxes</freightDetails>
</choice:Plane>

It seems to complain that there is no element, but I'm trying to find a way to validate against the type. I get the following error:

[Error] :1:100: cvc-elt.1: Cannot find the declaration of element 'choice:Plane'.

When it tries to load the document with the following code:

SchemaFactory factory =
    SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(schemaFile);

DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
parserFactory.setSchema(schema);
parserFactory.setNamespaceAware(true);
DocumentBuilder parser = parserFactory.newDocumentBuilder();

Document document = parser.parse(inputSource);

Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));

It fails when it gets to the:

Document document = parser.parse(inputSource);

Does anyone have any ideas on how I would be able to get this working? (Or a validator that supports this sort of behaviour?)

Thanks

Rob


This is because your schema has defined a type (Plane), but hasn't defined any permitted elements that use that type. A type on its own has no meaning outside of the schema itself.

You need to add an <xsd:element> to your schema. The simplest solution is to use an anonymous complex type within that, something like:

<xsd:element name="Plane">
  <xsd:complexType>
    <xsd:sequence>
        <xsd:element name="freightDetails" type="xsd:string" minOccurs="0"/>
        <xsd:element name="passengers" type="xsd:int" minOccurs="0"/>
    </xsd:sequence>
  </xsd:complexType>    
</xsd:element>


In your example schema, you have only defined a type named Plane, not an element named Plane. Add an element declaration to your schema and see what happens...

0

精彩评论

暂无评论...
验证码 换一张
取 消