Industrial IoT Authors: Pat Romanski, William Schmarzo, Elizabeth White, Stackify Blog, 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.

    IoT & Smart Cities Stories
    Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
    The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
    BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.