Microservices Expo Authors: Liz McMillan, Zakia Bouachraoui, Elizabeth White, Pat Romanski, Yeshim Deniz

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.

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


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.

    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
    The now mainstream platform changes stemming from the first Internet boom brought many changes but didn’t really change the basic relationship between servers and the applications running on them. In fact, that was sort of the point. In his session at 18th Cloud Expo, Gordon Haff, senior cloud strategy marketing and evangelism manager at Red Hat, will discuss how today’s workloads require a new model and a new platform for development and execution. The platform must handle a wide range of rec...
    When building large, cloud-based applications that operate at a high scale, it’s important to maintain a high availability and resilience to failures. In order to do that, you must be tolerant of failures, even in light of failures in other areas of your application. “Fly two mistakes high” is an old adage in the radio control airplane hobby. It means, fly high enough so that if you make a mistake, you can continue flying with room to still make mistakes. In his session at 18th Cloud Expo, Lee A...
    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...
    Lori MacVittie is a subject matter expert on emerging technology responsible for outbound evangelism across F5's entire product suite. MacVittie has extensive development and technical architecture experience in both high-tech and enterprise organizations, in addition to network and systems administration expertise. Prior to joining F5, MacVittie was an award-winning technology editor at Network Computing Magazine where she evaluated and tested application-focused technologies including app secu...
    Containers and Kubernetes allow for code portability across on-premise VMs, bare metal, or multiple cloud provider environments. Yet, despite this portability promise, developers may include configuration and application definitions that constrain or even eliminate application portability. In this session we'll describe best practices for "configuration as code" in a Kubernetes environment. We will demonstrate how a properly constructed containerized app can be deployed to both Amazon and Azure ...
    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...
    Using new techniques of information modeling, indexing, and processing, new cloud-based systems can support cloud-based workloads previously not possible for high-throughput insurance, banking, and case-based applications. In his session at 18th Cloud Expo, John Newton, CTO, Founder and Chairman of Alfresco, described how to scale cloud-based content management repositories to store, manage, and retrieve billions of documents and related information with fast and linear scalability. He addresse...
    SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
    Discussions of cloud computing have evolved in recent years from a focus on specific types of cloud, to a world of hybrid cloud, and to a world dominated by the APIs that make today's multi-cloud environments and hybrid clouds possible. In this Power Panel at 17th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the importance of customers being able to use the specific technologies they need, through environments and ecosystems that expose their APIs to make true ...
    In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...