Convert Attributes to Elements and Elements to Attributes

Transform elements into attributes and back the other way with XSLT.

You’re sitting in a conference room, leaning back in your chair. Opinions are flying back and forth across the room about whether to represent the XML data from a new application in either element or attribute form.

One engineer says, combing his beard with his fingers, “You don’t want to use attributes at all. What if down the line you need more than one attribute with the same name. You can’t do that in XML. You can only use one attribute with a given name.”

“Attributes contain metadata about elements,” another barks. “You don’t store metadata in element content. Period. That’s where the real data goes.”

You rock forward in your chair. “Excuse me,” you say with a chuckle, “but none of these arguments matter.” The room goes silent. Your project manager’s nostrils flare. “You better explain yourself,” she says, taking the last swig of her spring water.

“Gladly,” you say. “I’ve got a pair of XSLT stylesheets that can transform the data easily between element and attribute forms in seconds. Walk with me to my cubicle and I’ll give you a demo.”

In reference to the element-or-attribute debate, Michael Kay has wisely said: “Beginners always ask this question. Those with a little experience express their opinions passionately. Experts tell you there is no right answer” (http://lists.xml.org/archives/xml-dev/200006/msg00285.html). This hack will allow you to keep changing ...

Get XML Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.