: ) wonderful world ( :

the metasyntactic variable

check set inclusion with XPath

leave a comment »

In the XPath specification, Booleans section, you can read the following sentence about the = operator (in tests):

“If both objects to be compared are node-sets, then the comparison will be true if and only if there is a node in the first node-set and a node in the second node-set such that the result of performing the comparison on the string-values of the two nodes is true. [...]“

Hence you can test for an object being a member of a set of objects:

$ cat data.xml
<root>
  <nodes>
    <node>3</node>
    <node>8</node>
    <node>9</node>
    <node>2</node>
  </nodes>
  <ptrs>
    <ptr>1</ptr>
    <ptr>3</ptr>
  </ptrs>
</root>
$ cat selected.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml"/>

  <xsl:template match="//root">
    <nodes>
      <xsl:for-each select="//root/nodes/node">
        <selected>
          <xsl:value-of select="position() = //root/ptrs/ptr/text()" />
        </selected>
      </xsl:for-each>
    </nodes>
  </xsl:template>
</xsl:stylesheet>

$ xsltproc selected.xsl data.xml | xmllint --format -
<?xml version="1.0"?>
<nodes>
  <selected>true</selected>
  <selected>false</selected>
  <selected>true</selected>
  <selected>false</selected>
</nodes>
$

 

Advertisement

Written by grault

December 19, 2011 - 8:00 pm at December 19, 2011 - 8:00 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.