Is there a way to extend XSD elements with custom attributes?
For example, I'd like to do the following in an XSD:
<xs:element name="myElement" type="xs:string" myCustomAttribute="true" />
                Extending XSD with custom attributes can be accomplished by first defining the custom attributes in your own namespace, as follows:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           targetNamespace="http://www.mycompany.com" 
           elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:attribute name="myAttribute" type="xs:boolean" default="true"/>
</xs:schema>
In this namespace, http://www.mycompany.com, a single attribute named myAttribute is defined, with a type of xs:boolean.
Next, use this namespace in your target schema, as follows:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
           xmlns:mc="http://www.mycompany.com" 
           xsi:schemaLocation="http://www.mycompany.com ./doc.xsd" 
           elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="element1" mc:myAttribute="false"/>
</xs:schema>
In this example, the <schema> element includes attributes that define the custom namespace (xmlns:mc="http://www.mycompany.com"), and the location for the custom schema file (xsi:schemaLocation="http://www.mycompany.com ./doc.xsd"). 
The target schema contains a single element, "element1", and has the custom attribute myAttribute defined above, with a value of "false". Note that the name of the custom attribute is prefixed with the custom namespace prefix. Also note that if a value of an invalid type is used (example: mc:myAttribute="invalid"), a validation error will be generated.
Credit to @GhislainFourny and @kjhughes for help with this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With