The Mighty Blog

Single XML Schema Element with a Single Attribute

Dec 24

Written by:
12/24/2007  RssIcon

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" />
</xs:element>

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:complexType>
        <xs:simpleContent>
            <xs:extension base="xs:decimal">
                <xs:attribute name="myAttribute" type="xs:string" use="required" />
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
</xs:element>

Tags:
Categories: Technology

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Add Comment   Cancel 
Add to Technorati Favorites
Tweet about my blog
The opinions expressed here are the personal opinions of Will Strohl and do not necessarily represent the views and opinions of the DotNetNuke Corporation.
© Copyright 2004-2011 by Will Strohl. All rights reserved. Website Skinned By: Ralph Williams  Website Hosted By: Applied Innovations