Welcome!

Microservices Expo Authors: Liz McMillan, Pat Romanski, Elizabeth White, Stackify Blog, Andreas Grabner

Related Topics: Industrial IoT

Industrial IoT: Article

Sheddiing A Little Light on XML

Sheddiing A Little Light on XML

This month is a veritable potpourri of FAQs regarding XML. I've selected some questions that people have asked me time and time again. If there's one thing that I've learned as head geek, it's that if a single person e-mails me a question, there are probably a thousand others out there scratching their heads with the same question. Well, scratch no further. If I don't cover the question this month, it'll be answered in an upcoming column.

Q: How do I handle dates in XSLT?
A: Although dates are nicely addressed in the upcoming 2.0 spec of XSLT (patience, grasshopper), they're noticeably absent in the 1.0 working draft. For those of you who have wrestled with date handling, I expect to hear a collective "Whoo Hoo!" (spoken like Homer Simpson) as you read this section. Nonetheless, the need for functionality to handle dates would be nice to have right now. Dates are an important area in any database application. We all use them, but handling dates in XSLT is an uncertain process.

We've all become accustomed to working with programming languages that demonstrate a robust set of functions for handling dates. Although it's very likely that you can write your own set of date functions, why reinvent the wheel!

The following list includes resources that contain some robust date functions, which can be implemented directly into your XSLT files. These functions, templates, and techniques are selflessly donated by fellow programmers who wish to lighten the burden for the rest of us by shedding some light on the subject. Checking them out prior to embarking on an attempt to write your own might save some time and generate some ideas of your own. Here are a few examples.

1. Date sorting on a fixed-date format
Another approach is the use of substring functions to custom-tailor the sort order of date/time values. Substring functions give a pure XSLT implementation mixed with the flexibility to hit just about any section of XML input. Judging by the sample code in Listing 1, it becomes apparent that this technique can be extended to date/times of virtually any fixed format (yyyy/mm/dd, dd/mm/yyyy, hh:mm:ss).

In the "yyyy/mm/dd" example, we're first sorting on the year, then the month, then the day, so that we get the correct numerical sort. The other examples ("dd/mm/yyyy" and "hh:mm:ss") are variations of the principle (see Listing 1).

2. JavaScript date function library
If you search the Net long and hard, you will find code submitted by programmers dedicated to furthering the XML/XSLT cause. One great example is a collection of JavaScript date handling routines written by Kurt Cagle. These include convertToJSDate, AddInterval, DayOfWeekName, DayOfWeek, AddInterval and DateDiff, all of which can be found at none other than www.kurtcagle.net.

3. Date sorting on a translated date
The translate() function can be used in conjunction with substring functions to produce a concise, single-line date translation that can be used to create your date sort key. As with Example 1, this technique can also be extended to allow converting input into a numerical date sort key, even if it started out in a different format.

The following example takes a date format of "2001-01-25T10:05:53 PM" and converts it to: "20010125," which is then sorted numerically.

<xsl:sort select="translate
(substring-before(date,'T'), '-','')"
order="descending" data-type="number" />

4. Advanced date sorting: sorting by month names
Last, but not least, if you need to sort by a date that includes the name of the month, an advanced date-sorting technique was contributed to SnippetCentral.com by Dimitre Novatchev. In addition to showing how dates can be sorted by month names, this snippet also demonstrates the use of the Muenchen method as well as using (simulated) arrays in XSLT (see XML-J Web site for source code).

Note: The following solutions were selflessly contributed, along with implementations to demonstrate them, by the following members of our development community:

Q: Is it possible to convert a fixed-length text file to XML?
A: In an ideal world, we'll always receive our input file in the format that's easiest to work with, but in the real world we have to work with what we get. In the event that the input is a text file, it'll need to be handled a tad differently. But with a bit of effort, you can convert that text file into XML in short order.

In this example, the input file is a text file named Customers.txt, which contains one or more rows of input that is 72 characters wide. The algorithm that we'll use is as follows:
1. Reference the text file, Customers.txt, as a parsed entity. The end result will be that the element named "allcustomers" will contain the contents of the text file.

FixedLengthCombined.XML
<?XML version="1.0" encoding='utf-8' ?>
<!DOCTYPE allcustomers [
<!ENTITY resourceA SYSTEM "Customers.txt">
]>

<allcustomers>
&resourceA;
</allcustomers>

2. Access the "allcustomers" element and pass it to a template named "SplitFixedLengthToXML." As the name implies, this template will read through the string and create an element for all fixed-length strings contained within. At this level, the only two parameters necessary to pass to the template are:

  • The contents of the string
  • The length of each fixed-length string in the input file. As it processes the block of text, it will recursively convert one line at a time into the appropriate XML elements. (see Listing 2).

    3. The inner-workings of the "SplitFixedLengthToXML" involve creating an element for all sections of the single input line that it processes. As each single line is processed, the template is called again recursively with the input text minus the text that was just processed. This process will continue until all input lines are exhausted. The contents of the template, and the use of a template, TrimTrailing, to remove white space at the end of each string can be found on the XML-J Web site. This eliminates the additional spaces that by definition of a fixed-length string will very likely be at the end of each element.

    Gotchas
    In this solution, there are a few subtle gotchas to be aware of. First of all, text files may contain unescaped sensitive characters ("&," "<," and "]]>") that must be escaped for input to be well formed. (Yes, even though the input text is not originally in XML format, it must still be well formed to be handled by the XML processor.) No escaping = no processing. Last, in case you're wondering whether the character count is thrown off by escaping "<" into "&lt;" - it does not. The four file bytes still represent a single character and the XML processor will handle it as such.

    Cool XML Implementation of the Month
    While XML specifications surface on an almost daily basis, none hits home as much as the Election Markup Language (EML). You see, I'm from Miami, so this particular specification is one that's welcomed by me personally (not that they need my endorsement). The EML proposal would include specifications for exchanging data between election and voter registration systems developed by different hardware, software, and IT services vendors. Although we missed the chance to elect the guy who invented the Internet, this is a prime example of how XML is affecting so many aspects of our lives.

    On a related note, yours truly has created his own prototype of a Web-based voting system, the WeboVoteOmatic, found at www.XMLpitstop.com/WeboVoteOmatic. In reality, it just gives me an opportunity to poke fun at our political system (in a computer geek sort of way). Although it has yet to take advantage of the new EML specification, it illustrates some very useful techniques for both client and server-side XML coding. Depending on the flavor of the demo that you select (source code included), it demonstrates:

    1. XMLHTTP: Sending data between the client and server without refreshing the page (IE5+ only)
    2. Data Islands: Binding XML data to your HTML elements
    3. SQL Server 2000: Accessing InsertGrams, UpdateGrams, DeleteGrams
    4. BackEnd: Saving data to SQL Server 6.5, 7.0, and 2000, Access
    5. Cross Browser: Demonstration that works on all HTML 4+ browsers

    Send your questions to David at [email protected] He'll answer questions that fall into one or more of the following categories:

  • FAQ: What you always wanted to know
  • Black Belt: The toughest of the tough
  • Customizing XSLT: My personal favorite and by far the most popular
  • Going Wireless: Bring the world of wireless to your eyes.
  • More Stories By David Silverlight

    David Silverlight is the chief XML evangelist for Infoteria. He has
    been working in the trenches for a number of years as a software
    architect and consultant, specializing in database-driven Web
    applications. He also maintains www.xmlpitstop.com, a resource for
    XML examples, resources, and everything else XML.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    Microservices Articles
    Is advanced scheduling in Kubernetes achievable?Yes, however, how do you properly accommodate every real-life scenario that a Kubernetes user might encounter? How do you leverage advanced scheduling techniques to shape and describe each scenario in easy-to-use rules and configurations? In his session at @DevOpsSummit at 21st Cloud Expo, Oleg Chunikhin, CTO at Kublr, answered these questions and demonstrated techniques for implementing advanced scheduling. For example, using spot instances and co...
    Skeuomorphism usually means retaining existing design cues in something new that doesn’t actually need them. However, the concept of skeuomorphism can be thought of as relating more broadly to applying existing patterns to new technologies that, in fact, cry out for new approaches. In his session at DevOps Summit, Gordon Haff, Senior Cloud Strategy Marketing and Evangelism Manager at Red Hat, discussed why containers should be paired with new architectural practices such as microservices rathe...
    In his session at 20th Cloud Expo, Mike Johnston, an infrastructure engineer at Supergiant.io, will discuss how to use Kubernetes to setup a SaaS infrastructure for your business. Mike Johnston is an infrastructure engineer at Supergiant.io with over 12 years of experience designing, deploying, and maintaining server and workstation infrastructure at all scales. He has experience with brick and mortar data centers as well as cloud providers like Digital Ocean, Amazon Web Services, and Rackspace....
    SYS-CON Events announced today the Kubernetes and Google Container Engine Workshop, being held November 3, 2016, in conjunction with @DevOpsSummit at 19th Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA. This workshop led by Sebastian Scheele introduces participants to Kubernetes and Google Container Engine (GKE). Through a combination of instructor-led presentations, demonstrations, and hands-on labs, students learn the key concepts and practices for deploying and maintainin...
    Docker is sweeping across startups and enterprises alike, changing the way we build and ship applications. It's the most prominent and widely known software container platform, and it's particularly useful for eliminating common challenges when collaborating on code (like the "it works on my machine" phenomenon that most devs know all too well). With Docker, you can run and manage apps side-by-side - in isolated containers - resulting in better compute density. It's something that many developer...
    Modern software design has fundamentally changed how we manage applications, causing many to turn to containers as the new virtual machine for resource management. As container adoption grows beyond stateless applications to stateful workloads, the need for persistent storage is foundational - something customers routinely cite as a top pain point. In his session at @DevOpsSummit at 21st Cloud Expo, Bill Borsari, Head of Systems Engineering at Datera, explored how organizations can reap the bene...
    As software becomes more and more complex, we, as software developers, have been splitting up our code into smaller and smaller components. This is also true for the environment in which we run our code: going from bare metal, to VMs to the modern-day Cloud Native world of containers, schedulers and micro services. While we have figured out how to run containerized applications in the cloud using schedulers, we've yet to come up with a good solution to bridge the gap between getting your contain...
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    DevOps is speeding towards the IT world like a freight train and the hype around it is deafening. There is no reason to be afraid of this change as it is the natural reaction to the agile movement that revolutionized development just a few years ago. By definition, DevOps is the natural alignment of IT performance to business profitability. The relevance of this has yet to be quantified but it has been suggested that the route to the CEO’s chair will come from the IT leaders that successfully ma...
    Skeuomorphism usually means retaining existing design cues in something new that doesn’t actually need them. However, the concept of skeuomorphism can be thought of as relating more broadly to applying existing patterns to new technologies that, in fact, cry out for new approaches. In his session at DevOps Summit, Gordon Haff, Senior Cloud Strategy Marketing and Evangelism Manager at Red Hat, will discuss why containers should be paired with new architectural practices such as microservices ra...