Using XSD to generate class for schemas which use imports

I’ve always prefer to use class based messaging in BizTalk. This is pretty straightforward and involves generating classes from schemas using the XSD.exe tool supplied.

Because I treat messages in BizTalk the same way that DTO’s are used in traditional domain driven development – the are merely a mechanism of passing data from the UI (or in my case an integration point) to the next layer.

However, I came across an error generating the class today referring to an ‘element is not declared’

image

After some head scratching I realised that it was complaining about a node that I’d imported from another schema. I guess this would have caused the generator a bit of a problem. Thankfully Google came to the rescue with this post from Martin Brown . I reproduce the code here (the post is almost 8 years old);

Schema 1

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema targetNamespace="http://example.com/XMLSchema1.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:examp1="http://example.com/XMLSchema1.xsd"
    xmlns:examp2="http://example.com/XMLSchema2.xsd">

    <xs:import namespace="http://example.com/XMLSchema2.xsd" schemaLocation="XMLSchema2.xsd" />

   <xs:element name="example">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="test" type="examp2:myType" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Schema 2

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema targetNamespace="http://example.com/XMLSchema2.xsd"
    xmlns:examp2="http://example.com/XMLSchema2.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:complexType name="myType">
        <xs:sequence>
            <xs:element name="test" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>

So, the key trick is to pass in the imported schema in the XSD command line. The other thing to remember if you aren’t setting the output filename is to put the “real” instance schema at the end of the list of schemas otherwise you’ll get a file named after your imported schema.

xsd.exe schema1.xsd schema2.xsd /c

Thanks google!

Leave a Reply

Post Comment