user3783403
user3783403

Reputation: 1

XSL to replace tags/elements and resave file?

I don't have a lot of experience in XSL functions.

I have a variety of existing files, and will have a constant pile of new files, that are various 'flavours' of XML. NITF, etc.

What I would like to do, is process all the XML files, and replace certain elements with new element names, and resave them.

Using Oxygen as an app. The files will eventually be ingested by a DAM.

i.e. in an XML file, the following code:

<abstract>
    <hl2>Mercy for Animals doesn’t work on tips. Its investigators go where they get hired, with cameras.</hl2>
</abstract>

I'd like to make this code:

<title>
    <hl2>Mercy for Animals doesn’t work on tips. Its investigators go where they get hired, with cameras.</hl2>
</title>

So a simple search and replace, of XML files, and then to resave them out, save file name, etc., and keep structure etc.

And can the code have different transforms added to it?

Basically the reason is to ingest various XML files from various sources, into a XML format that our DAM requires. Perhaps an XSL-FO?

Upvotes: 0

Views: 49

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

When you have an XSLT problem that amounts to "keep most things the same but tweak X, Y and Z" the standard answer is to use an "identity transformation". This is a single template that will copy the input document to the output unchanged, but which can be selectively overridden by other more specific templates to make modifications. At its most basic this means

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <!-- identity template - copy everything verbatim except for ... -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <!-- ... abstract elements, which we rename to title -->
  <xsl:template match="abstract">
    <title>
      <xsl:apply-templates select="@*|node()" />
    </title>
  </xsl:template>
</xsl:stylesheet>

but if your input documents involve any namespaces then you need to adjust your match expressions appropriately. E.g. if the input document has xmlns="http://example.com" then all the unprefixed elements in the document belong to that namespace and in order to match them in XSLT you need to create a prefix binding and use that in the match:

<xsl:stylesheet ....
      xmlns:ex="http://example.com">

  <xsl:template match="ex:abstract">

as unprefixed names in match patterns and XPath expressions always mean nodes in no namespace.

Upvotes: 1

Related Questions