Tag Archives: XML - Page 3

Validate both element and attribute with XSD

I have this XML snippet that I need to validate:


I want to validate both the attribute ‘model’ content and the element content ‘Volvo’. Here is one way of doing it (thank you Alex):


        <xs:attribute name="model" type="xsd:string"/>


The base attribute will validate the element content ‘Volvo’ and the attribute type will validate the ‘model’

Validate XML element or attribute against multiple patterns in a XSD

Every now and then you need to validate an element or attribute agains multiple patterns.
Say an element is allowed to contain a date both in ‘YYYYnn’ format (where nn is the week number) and ‘seasonYY’ format. To solve this I use the following xsd pattern:

           <xs:pattern value="(19|20[0-9]{2}[0-5][0-9]) | (summer[0-9]{2}) | (winter[0-9]{2}) | (fall[0-9]{2}) | (spring[0-9]{2})"/>

The solution to my problem lies in the ‘|’ and parenthesis. I group the different patterns in parenthesis and separate the patterns with the OR-operator ‘|’. This way I can validate both syntaxes YYYYnn and seasonYY – only one needs to be true

There are of course other ways (shorter) to write the pattern but I choose this way because I believe it is easier to understand.

Pretty XML in the Smultron Editor

This is a function I often use to help me read XML from various systems. It’s not in the default package of Tools in Smultron so you have to create it yourself.

1. First open the Commands Window (Tools->Handle Commands->Show Command Window)

2. Create a new command and give it a name (Create Command button)

3. Paste the following code in the lower pane of the window:

cat %%s | /usr/bin/tidy -indent -quiet -xml -wrap 100

4. Tick the ‘Inline’ option

5. Close the Command Window

Now you can open or paste a one row xml document into the editor, select the XML, copy it to clipboard and then run the command (Tool->Command->YourCommand) and voila! The XML is now in pretty format!

This works at least in Smultron version 3.6b1 which is the version I use