Sometimes XML becomes a bit weird with namespace declarations all over the place. This XSLT cleans that up. Stumbled upon in a StackOverflow answer I don’t find anymore and put here so I know where to find it in the future.
Needed to check some XML output from a CalDAV service so I used curl, which is nice and simple. Only problem was that all the XML came back on a single long unreadable line. Turned out it wasn’t too difficult to get it formatted:
The key part here is of course the piping into xmllint. --format tells it to format the XML and the - tells it to read the XML from standard in. The dash can be swapped with the path to an XML file, if you need to format already downloaded XML.
I recently discovered Meddler which is an HTTP generator based on JScript. Since there were not many samples to find and Google wasn’t really of much help here, I figured I could share the scripts I write here. Maybe it helps someone out, and even more likely, I will probably have to look back at this at some time since I will forget 😛
Here’s how to do a simple XSLT transformation using only classes in vanilla Java 1.5 (maybe even 1.4?), no external libraries or anything. The classes are found in the javax.xml.transform package.
// Create a factory
TransformerFactory tf = TransformerFactory.newInstance(); if(!tf.getFeature(SAXTransformerFactory.FEATURE)) thrownewRuntimeException("Did not find a SAX-compatible TransformerFactory.");
SAXTransformerFactory stf =(SAXTransformerFactory) tf;
// Create a reusable template for the XSLT
Templates xslt = stf.newTemplates(new SourceStream(inputStreamWithXslt));
// Use the template to transform some XML
templates.newTransformer().transform( new StreamSource(inputStreamWithXml), new StreamResult(System.out));
I got an XML file from a web service which had a default namespace and a namespace prefix with equal paths. In addition I had to change the root node which then lost all its defined namespaces. This resulted in various namespaces being redeclared on a bunch of various child elements, while it really should just need to be declared once on the root node.
<!-- Make all elements with dup prefix use default namespace so we avoid ugly mix of both --> <xsl:templatematch="dup:*"> <xsl:elementname="{local-name()}"> <xsl:apply-templatesselect="@* | node()"/> </xsl:element> </xsl:template>
<!-- For the document element (top element) --> <xsl:templatematch="/*"> <xsl:copy> <!-- Add namespace to prevent redeclaration on every child element using it --> <xsl:namespacename="xsi"select="'http://www.w3.org/2001/XMLSchema-instance'"/> <!-- Copy attributes and child elements --> <xsl:apply-templatesselect="@*|node()"/> </xsl:copy> </xsl:template>