Skip to content

Formatting Your XML

Although Xojo does not have a built-in method to format XML text, you can use XSLT to do this for you. XSLT stands for eXtensible Stylesheet Language. This XSLT can be used to format XML:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/">
<xsl:copy-of select="/" />
</xsl:template>
</xsl:transform>

To use this with Xojo, add a module to your project (name it XMLExtensions), add a String constant to the module (call it kXSLTFormat) and copy the above XSLT into the constant.

Now add a Global function to the module that extends the XMLDocument class with a Format function:

Function Format(Extends xml As XMLDocument) As String
  Return xml.Transform(kXSLTFormat)
End Function

Now you can call it to get back formatted XML as a String. For example, this code takes unformatted XML from a TextField and displays the formatted XML in another TextField:

Dim xml As New XMLDocument
xml.LoadXml(TextArea1.Text)
TextArea2.Text = xml.Format