Will "the Mighty" Strohl

Single XML Schema Element with a Single Attribute

First of all, happy holidays to everyone that celebrates something this time of year.  :)  I have been hand-coding quite a few XML schema files (XSD) recently.  Writing it is easy enough, but I just ran into what seemed like a very thing to write - that is until I actually begun to write it.

I wanted to define a single XML element that has a value, and a single attribute.  It would look like this:

<myElement myAttribute="textvalue">123.45</myElement>

Well, my first instinct was to write it like this:

<xs:element name="myElement" type="xs:decimal" minOccurs="0" maxOccurs="1">
    <xs:attribute name="myAttribute" type="xs:string" use="required" />

However, with Visual Studio being the trusty side kick that it is, it quickly let me know that my code was invalid.  D'oh!

I then begun toying with a few variations of it, and then even quickly looked through the W3School Schema Reference, before turning to a forum.

Right after I made that post, a light bulb suddenly lit up in my head.  I know how to show myself how to do this!

Visual Studio has a really cool tool that is built in that will write schema definitions for you.  I don't usually use it though, because it does not write the schema in an extensible way.  However, in this very situation, the tool was a life saver. I simply created an XML document with the element structure I wanted.  Then, I selected the "Create Schema" option from the XML menu (only available when viewing the XML document).

Whalla!!  The schema was created and opened right before me eyes!

Here is how to define the XML from above:

<xs:element name="myElement">
            <xs:extension base="xs:decimal">
                <xs:attribute name="myAttribute" type="xs:string" use="required" />

blog comments powered by Disqus