Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Invalid content was found starting with element 'X'. One of '{X}' is expected

Tags:

java

xml

xsd

I'm trying to validate a simple XML using a simple XSD, but always get this error:

cvc-complex-type.2.4.a: Invalid content was found starting with element 'linux'. One of '{linux}' is expected.

Why? The tag 'linux' is found and is one of {linux}!

java code:

public static void main(String[] args) {
    try {
        InputStream xml = new FileInputStream("data/test.xml");
        InputStream xsd = new FileInputStream("data/test.xsd");

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));

        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));

        log.info("OK!");
    } catch (Exception e) {
        log.error(":(");
        log.error(e.getMessage());
    }
}

data/test.xml:

<?xml version="1.0" encoding="utf-8"?>
<so xmlns="http://test/">
    <linux>
        <debian>true</debian>
        <fedora>true</fedora>
    </linux>
</so>

data/test.xsd

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema targetNamespace="http://test/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="so">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="linux">
                    <xs:complexType>
                        <xs:sequence minOccurs="1" maxOccurs="unbounded">
                            <xs:any processContents="lax" maxOccurs="unbounded"/>
                        </xs:sequence></xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
like image 898
Eduardo Avatar asked Dec 07 '25 03:12

Eduardo


1 Answers

Because the schema does not specify elementFormDefault="qualified", the local element declaration of element "linux" is declaring an element in no namespace, but the instance has a linux element in namespace "http://test/". The error message is confusing because it fails to make clear that the problem is with the namespace.

like image 71
Michael Kay Avatar answered Dec 08 '25 15:12

Michael Kay