woensdag 8 april 2009

Declare element to be space preserving in XSD

Today i was working with a self-defined XML format. One element type in my xml files is the <scriptblock> element. This element contains snippets of script code.

When i was finished composing my XML file in my XML editor, told the editor to autoformat the XML document. Autoformatting is a tool, i use it about every 10 seconds when writing source code. However, in this case the autoformatter screwed up my <scriptblock> elements: It treated the contents like plain text, just pasting all code in a single text paragraph. New lines started halfway comment strings or String arguments, and all indentation was lost.

Obviously, for source code, layout is important and i wanted a way to make sure that XML processors like the autoformatter would keep their hands off my carefully applied manual formatting in the <scriptblock> elements...

That turned out to be pretty easy: in the .xsd (schema definition) for my xml format, i had to add an attribute called "xml:space" with the "scriptblock" element type, and set it to fixed value "preserve".


<xs:element
name="scriptblock"
minOccurs="0">
<xs:complexType>
<xs:simpleContent>
<xs:extension
base="xs:string">
<xs:attribute
ref="xml:space"
fixed="preserve" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>


This attribute refers to an externally defined attribute (xml:space). Hence, you must import the xml namespace definition in the top of your document, and also declare the xml namespace in your schema element:

<xs:schema
targetNamespace="http://www.yourcompany.com"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns="http://www.yourcompany.com">

<xs:import
namespace="http://www.w3.org/XML/1998/namespace"
schemaLocation="http://www.w3.org/2001/xml.xsd" />



After that, the autoformatter left my code blocks alone, and formatting was preserved. (Although i had to re-start the XML editor first.)

Hope this is useful for some.

Mike

Geen opmerkingen:

Een reactie posten