0

Is there a way to copy 2 or 3 nodes of XML to a variable using XSLT? I'm looking for nodes and not the node values.

My sample XML is:

<node1>
  <node2>
    <node3>abc</node3> 
    <node4>def</node4> 
  </node2>
</node1>
<node1>
  <node2>
    <node3>123</node3> 
    <node4>456</node4> 
  </node2>
</node1>

And my XSLT sample is:

<xsl:for-each select="/node1/node2">
  <xsl:if test="current()/node4 ! = '456'">
    <xsl:copy-of select="./node3" />
    <xsl:copy-of select="./node4" />
  </xsl:if>
</xsl:foreach>

The problem with this is that I'm getting node4 everytime as the first node of the XML instead of current one. On node3 I'm getting the current one and there's no problem.

zx485
  • 28,498
  • 28
  • 50
  • 59
rgu
  • 1
  • my output should be values of node3 and node4 as a flat file, and duplicates should be eliminated. And also it should perform really fast, as the input is huge like 20MB. – rgu Dec 29 '16 at 21:53

2 Answers2

0

Your problem may be caused by the RTF(Resulting Tree Fragment) problem of XSLT-1.0:

A variable cannot contain a nodeset (but only a RTF)

I explained this problem in this SO answer.

RTFs cannot be queried by XPath-1.0 expressions, so they are only useful in a very limited subset of situations.

One solution would be using the newer XSLT-2.0.

Community
  • 1
  • 1
zx485
  • 28,498
  • 28
  • 50
  • 59
  • Thank you @zx485. Is there any workaround for this problem instead of using xslt 2.0? – rgu Dec 29 '16 at 22:06
  • @rgu: Unfortunately none that I know of :-( Otherwise I would have included that in my answer. – zx485 Dec 29 '16 at 22:13
  • You can convert a rtf to a node-set using the node-set function. See the link: http://www.xml.com/pub/a/2003/07/16/nodeset.html – John Ernst Dec 29 '16 at 23:35
0

It may help you to just select the nodes that you want all at once.

<xsl:variable name="sample">
   <xsl:copy-of select="/node1/node2[node4!='456']/*[name()='node3' or name()='node4']"/>
</xsl:variable>
John Ernst
  • 1,206
  • 1
  • 7
  • 11