Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Tip: Creating valid XML with object-oriented programming

Squeezing OOP data into XML rules

David Mertz (mertz@gnosis.cx), Gesticulator, Gnosis Software, Inc.
Author photo: David Mertz
David Mertz uses a wholly unstructured brain to write about structured document formats. David may be reached at mertz@gnosis.cx; his life pored over at http://gnosis.cx/dW/.

Summary:  In this tip, David offers some techniques that programmers in object-oriented languages can use programmatically to ensure the validity of XML documents at the time of their creation.

View more content in this series

Date:  01 Mar 2002
Level:  Introductory

Comments:  

XML has something of a dual identity. On the one hand, in its SGML roots, XML is a way of expressing formally and rigidly structured data; DTDs and XML Schemas describe these structures. On the other hand, as seen in popular APIs -- DOM, SAX, and XSLT, but also by other XML libraries -- XML is merely a way of indicating generically hierarchical data. Unfortunately, the two sides communicate poorly. The creation of valid documents falls outside these APIs (validation is usually relegated to the parse phase). However, by using just a few special strategies one can at least get OOP objects to look a lot like valid XML.

What makes up validity?

The sorts of validity constraints you can express with a DTD differ somewhat from those you can express with a W3C XML Schema. For this tip, I'll focus on issues common to the different validity constraint specification styles.

The basic idea of XML validity is to specify what can occur inside an element, how often it can occur, and what alternatives exist for what can occur. In addition, when multiple things can occur inside an element, the order of occurrence can be specified (or left open, as needed). Let's look at a highly simplified hypothetical dissertation.dtd:


A "dissertation" DTD with all basic constraints
                <!ELEMENT dissertation (dedication?, chapter+, appendix*)>
<!ELEMENT dedication (#PCDATA)>
<!ELEMENT chapter (title, paragraph+)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT paragraph (#PCDATA | figure | table)>
<!ELEMENT figure EMPTY>
<!ELEMENT table EMPTY>
<!ELEMENT appendix (#PCDATA)>

In other words, a dissertation may contain one dedication, must contain one or more chapters, and may contain zero or more appendices. The various subelements occur in the listed order (if at all). Some elements contain only character data. In the case of the <paragraph> tag, it may contain either character data or a <figure> subelement or a <table> subelement. Structures can nest, but every basic validity concept is included in the example.


Making an object look like a document

Although DOM does not do so, OOP languages have all the basic data structures to represent validity (some languages more completely than others). The trick, basically, is to create objects whose attributes are constrained so as to permit only allowable things into them. Whether this is done at compile time or runtime depends on the language used, but either approach can introduce necessary constraints. In any case, the right sorts of objects must be created for each document type, not generically for all of XML.

XML documents are hierarchical, and objects that can contain other objects as attributes are likewise hierarchical. We just need to pick a few object types for the various attributes.

At the document root -- and at other levels beneath it -- we want to specify the children that can occur, and their order. Two approaches come to mind. One option is to create a heterogeneous sequence of those things that occur in the element. Haskell and Python tuples have the nice quality of being immutable (as are, for example, Fortran records), but a regular list or array (e.g. of void pointers) can serve also. For example, in Ruby we might "declare":


Init'ing Ruby "Root" class with member "part"
                dissertation = Root.new [ Maybe_dedication.new, \
                          Some_chapter.new, \
                          Any_appendix.new ]
# Example of accessing part of root element sequence
dissertation.part[1].addchapter(some, arguments, here)

The example leaves open exactly what the classes Maybe_dedication, Some_chapter, and Any_appendix do, but contains the sequence idea. dissertation is an instance of the class Root, whose job it is to hold a sequence (and probably has a few other methods, like writing the XML or validating the current instance).

A second approach, which is easier in many languages, is to make the things occur as root attributes directly, but reserve a special attribute that indicates the sequence. For example, Java might do something like:


Java class to hold dissertation parts as members
                public class dissertation {
    Maybe dedication = new Maybe(dedication_type);
    Some chapters = new Some(chapter_type);
    Any appendices = new Any(appendix_type);
    Seq _seq = new Seq[] {dedication, chapters, appendices};
}
/* Access is somewhat more natural now */
dissertation.chapter.add(some, arguments, here);


Expressing quantification

We have seen that the "parts" of elements can be allowed to occur in various numbers: one or zero; one or more; zero or more. We need objects to represent these quantities. The possibility case (zero or more) is straightforward, represented by standard (homogeneous) sequences: lists, arrays, vectors, or whatever the language calls them and provides. In order to provide other behaviors, it is probably worth wrapping a basic sequence in a custom class.

The limitation case (one or zero, i.e. not more than one) has a less obvious structure. Most likely a Maybe class (and descendants like Maybe_dedication) should be built around a basic sequence object, with guards against adding more than one thing in the provided methods. This is similar to our example for the existential case (one or more). So let's look at a possible (incomplete) Python implementation:


Python class to hold "one or more" things
                
                class ExistentialList(UserList.UserList):
    def __init__(self, tag=None, initlist=[]):
        if tag is None:
            raise ValueError, "Must specify tag name"
        self.tag = tag
        UserList.UserList.__init__(self, initlist)
    def __delitem__(self, i):
        del self.data[i]
        self.validate()
    def __repr__(self):
        self.validate()
        return
                '\n'.join(['<%s>%s</%s>' % (self.tag, item, self.tag)
                          for item in self.data])
    def validate(self):
        if
                not len(initlist):
            raise
                "ExistentialError", "List must have length >= 1"
            

A more robust example might add features like checks for proper item types in the .append(), .extend(), .__setitem__(), and other methods that can add to the list. A language with static typing would simply declare the type of things in the list, but would use a similar validation of size. In C++, one might use templates and generic programming to implement the general features of an ExistentialList, but specialize to subelement type.

An important feature for every object that represents a subelement is the ability to serialize itself to XML. Python reserves a "magic" method called __repr__(); other languages might use a method called .write() or .toXML(). The serialization also needs to descend recursively into children, which is handled automatically by Python with the magic method. In other cases, some manual calls on attribute objects are needed.


Expressing disjunctions

Alternation between occurrence patterns is more difficult to express in most OOP languages. There are a few languages -- like Pascal, Fortran, and most elegantly Haskell -- that allow enumerated types (discriminated union), but these are the exception, not the rule. In most languages, you just have to add custom checking to make sure one of the allowable items is contained by an instance.

One might program polymorphic constructor functions, perhaps by providing multiple type signatures to the constructors. Each allowable thing in an alternation pattern would have a constructor (including, possibly, sequence types where quantifiers are used with the disjoins in the DTD).

However, a more flexible approach is to use a generic framework that receives its alternation list either via initialization arguments, or by inheritence from an Or superclass. Such a child might look like:


Python specialization of Or abstract class
                
                class paragraph(Or):
    disjoins = (PCDATA, figure, table)

Assuming that the base functionality of the abstract class Or knows to look for a disjoins class member, this could be sufficient specialization. Naturally, guarded setters and getters need be defined in the parent (in the Python case, probably with magic methods).


Conclusion

Using data classes with some constraints on the values contained therein allows us to mirror the validity requirements of XML documents. Containment of classes can be structured in the same manner as containment of subelements. With a good framework of base classes in place, you can basically copy a DTD directly into a set of class definitions or initializations. Instances become members of other instances, and eventually you wind up with a root object instance that, along with its attributes, has various methods for manipulating data in ways that cannot break the validity requirements (in contrast to how easily one can break validity with basic types like strings and arrays). At the end of the manipulation, the root object should have some method for writing out the XML -- recursively descending into its attribute instances -- which produces a fully grown valid XML document. An ExistentialList, for example, can contain other ExistentialList objects -- nested serialization (the print statement) works beautifully with the given sample.

A final side note: Although no examples were presented here, Eiffel's "programming-by-contract" is particularly well suited to indicating the constraints discussed in this tip.


Resources


About the author

Author photo: David Mertz

David Mertz uses a wholly unstructured brain to write about structured document formats. David may be reached at mertz@gnosis.cx; his life pored over at http://gnosis.cx/dW/.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=12088
ArticleTitle=Tip: Creating valid XML with object-oriented programming
publish-date=03012002
author1-email=mertz@gnosis.cx
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).