Tienus McVinger
Tienus McVinger

Reputation: 477

Validate element (regex) and attribute (string)

My issue is as follows: In my xml file, I have the following bit:

<duration notation="mm:ss">03:14</duration>

Now, I need to validate this little bit in my xml schema. If the value of this element were a simple string with no further attention needed, I could've just done:

<xs:element name="duration" type="durationType" maxOccurs="1"/>

<xs:complexType name="durationType">
    <xs:simpleContent>
        <xs:extension base="xs:string">
            <xs:attribute name="notation" type="xs:string" fixed="mm:ss"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

Unfortunately, I want to validate the value in this element using Regex. Were that the only thing I needed to validate, I would've used:

<xs:simpleType name="durationType">
    <xs:restriction base="xs:string">
        <xs:pattern value="\d{1,2}:\d{2}"/>
    </xs:restriction>
</xs:simpleType>

My issue is that I just can't seem to figure out how to validate both at once. Been browsing the internet for hours (as you may be able to tell, the complexType piece of code is straight from an answer here on StackOverflow ;) ), but to no avail.

Upvotes: 1

Views: 286

Answers (1)

helderdarocha
helderdarocha

Reputation: 23637

Rename the simple type which validates the tag's content with a different name (e.g. durationContent):

<xs:simpleType name="durationContent">
    <xs:restriction base="xs:string">
        <xs:pattern value="\d{1,2}:\d{2}"/>
    </xs:restriction>
</xs:simpleType> 

Now simply use that type as a base for your extension, which adds an attribute:

<xs:complexType name="durationType">
    <xs:simpleContent>
        <xs:extension base="durationContent">
            <xs:attribute name="notation" type="xs:string" fixed="mm:ss"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

Now it validates both the attribute and the tag's content.

Upvotes: 2

Related Questions