Copy value of node using reference into other node

252 Views Asked by At

I'm trying to copy the value of an XML node referenced by an identifier into another node of the graph. The orignal file looks like this:

<Root>
<Object id="Id1">
    <FileName>file.png</FileName>
</Object>
<Description>
    <Content>
        <Title>Nice Object</Title>
        <ObjectReference>Id1</ObjectReference>
    </Content>
</Description></Root>

In XSLT, I use a variable to identify the value of the reference node identifier.

<xsl:template match="Content">
<xsl:variable name="IdObject">
    <xsl:value-of select="ObjectReference"/>
</xsl:variable>
<Out>
    <Title>
        <xsl:value-of select="Title"/>
    </Title>
    <FileName>
        <xsl:value-of select="//Object[@id='$IdObject']/Filename"/>
    </FileName>
</Out></xsl:template>

The value of 'FileName' is not copied. I select the wrong reference node, I think. I tried with 'Ancestor::' and 'Parent::'. That doesn't work either. Do you have an idea? Thanks I would like to obtain the following result :

<Out>
    <Name>Nice Object</Name>
    <FileName>file.png</FileName>
</Out>
1

There are 1 best solutions below

0
On BEST ANSWER

XSLT has a built-in key mechanism for resolving cross-references. The following stylesheet:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="obj" match="Object" use="@id" />

<xsl:template match="Content">
    <Out>
        <xsl:copy-of select="Title"/>
        <xsl:copy-of select="key('obj', ObjectReference)/FileName"/>
    </Out>
</xsl:template>

<xsl:template match="text()"/>

</xsl:stylesheet>

applied to your input example, will return:

Result

<?xml version="1.0" encoding="UTF-8"?>
<Out>
  <Title>Nice Object</Title>
  <FileName>file.png</FileName>
</Out>

P.S. Your attempt did not work because:

  1. You quoted the reference to the variable;
  2. You used Filename instead of FileName.