tags:

views:

51

answers:

1

I have an XML where a text node with value "null tag" appears (randomly) at the different places in the file.
My question is how to replace the text with some other text, where the element (and parent node) name is unknown. I have already created an XSLT file which looks a bit bulky and I am not sure about its efficiency in transformation time.

This is the sample test XML I have created:

<root>
  <sub_root>abc</sub_root>
  <sub_root>
    <child>test value</child>
    <child2>test value</child2>
    <sub_child>
      <node1>data</node1>
      <node2>data2</node2>
      <node3>
        <grand_child>test value</grand_child>
      </node3>
      <node4>test value</node4>
    </sub_child>
  </sub_root>
</root>

This is the XSLT :

  <xsl:template match="@*|*|text()">
        <xsl:copy>
          <xsl:choose>
            <xsl:when test="text()='test value'">
              <xsl:apply-templates select="@*|*"/>
              <xsl:text>replaced</xsl:text>
            </xsl:when>
            <xsl:otherwise>
              <xsl:apply-templates select="@*|*|text()"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:copy>
  </xsl:template>

This is the desired output, I am trying to generate:

<root>
  <sub_root>abc</sub_root>
  <sub_root>
    <child>replaced</child>
    <child2>replaced</child2>
    <sub_child>
      <node1>data</node1>
      <node2>data2</node2>
      <node3>
        <grand_child>replaced</grand_child>
      </node3>
      <node4>replaced</node4>
    </sub_child>
  </sub_root>
</root>

can this code be written in yet more better way(in any terms)? Or is that my code is better enough?

+5  A: 

Just add this to the identity transform:

<xsl:template match="text()[. = 'test value']">
    <xsl:text>replaced</xsl:text>
</xsl:template>

The result will copy every node in the input, unmodified, to the output - except for text nodes whose value is test value, which will be transformed into text nodes with the value replaced.

Robert Rossney
yup this is reduces the abstractness in my code .. :-) thanx ..
infant programmer