While writing a Munin plugin for the house's heatpump system, I needed to transform an XML file into something plain text that could be grepped easily.
XSLT is the premier solution to convert XML, so I used it. To avoid disambiguities, I needed to be able to grep for the full XML node path. Unfortunately, XSLT does not provide a native way to obtain the path.
By calling a template that prints the current element name and calls itself for its own parent element, I made it work:
Example XML
<?xml version="1.0"> <PCOWEB> <PCO> <ANALOG> <VARIABLE> <INDEX>1</INDEX> <VALUE>23.0</VALUE> </VARIABLE> <VARIABLE> <INDEX>2</INDEX> <VALUE>0.42</VALUE> </VARIABLE> </ANALOG> </PCO> </PCOWEB>
Path-generating XSLT
<?xml version="1.0"?> <stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform"> <template match="/PCOWEB/PCO/*/VARIABLE"> <call-template name="path"/> <value-of select="INDEX"/> <text> </text> <value-of select="VALUE"/> </template> <template name="path"> <for-each select="parent::*"> <call-template name="path"/> </for-each> <value-of select="name()"/> <text>/</text> </template> </stylesheet>