Reputation: 3204
In XSLT I often match nodes using the following command
<xsl:template match="*[local-name() = 'Proposal']/*[local-name() = 'ApplicationData']">
which would get the nodes from
<?xml version="1.0" encoding="utf-8"?><?xfa generator="XFA2_4" APIVersion="2.8.9029.0"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/" timeStamp="2013-03-01T09:48:58Z" uuid="3e3468da-104d-4532-8077-0dc001ca166b">
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
<Proposal xmlns="http://www.govtalk.gov.uk/planning/OneAppProposal-2006" Version="">
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</Proposal>
...
matching
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
How could I determine whether ApplicationData
existed, and if not, insert it?
Upvotes: 1
Views: 86
Reputation: 70628
You would need to add the logic to a template that matched the 'Proposal' element
<xsl:template match="*[local-name() = 'Proposal']">
Then, you would just write an xsl:if
statement, like so:
<xsl:if test="not(*[local-name() = 'ApplicationData'])">
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</xsl:if>
You would need to wrap this in an xsl:copy
if you wanted to retain the Proposal
element.
If you didn't already have an existing template matching Proposal
in your XSLT, you could add the test to template match itself
<xsl:template match="*[local-name() = 'Proposal'][not(*[local-name() = 'ApplicationData'])]">
<xsl:copy>
<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</xsl:copy>
</xsl:template>
As michael.hor257k mentioned in comments, it would be much cleaner if you declared your namespaces in your XSLT, and used namespace prefixes in the matching....
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
<xsl:template match="oneapp:Proposal[not(oneapp:ApplicationData)]">
<xsl:copy>
<oneapp:ApplicationData>
<oneapp:TreesHedgesWales/>
<oneapp:OtherLowCarbonEnergy/>
</oneapp:ApplicationData>
</xsl:copy>
</xsl:template>
Upvotes: 1