Search

Is it possible to grab parent node and only specific child nodes?

Example data:

<parent>
  <child id="1" />
  <child id="2" />
  <child id="3" />
</parent>

Wanted example result:

<parent>
  <child id="1" />
</parent>

Something like this ought to do the trick:

/parent/descendant-or-self::node()[@id = 1]

Like this?

I get only <child id="1" />.

You can try using the Ninja Utility with one extra template:

<xsl:template match="parent" mode="html">
    <xsl:apply-templates select="child[@id = '1']" mode="html"/>
</xsl:template>

Bear in mind though that with such an abstract question and XML-example you'll only get abstract answers. If you have a more concrete situation and some real XML we might be able to see more clearly what you're after.

@milka your gist has been deleted so I can't see what you had in mind; however when you say you "get only <child id="1"/>", I'm inclined to reply that this is the result you originally asked for:

<parent>
  <child id="1" />
</parent>

So help me understand what you see as different and then we can go further with you.

Hello and thanks for the replies. My approach to the problem wasn't right at first place so, please forget this thread.

But as an answer to wjnielsen, I got only the child element, and I needed the child element and the parent.

Here's a... xpathr/gist? ...I created a moment ago: http://xpathr.com/view/1868793/

That expression is unnecessarily complicated, you can do it like

  <xsl:template match="/">
    <xsl:copy-of select="parent//*[@id = 1]" />
  </xsl:template>

Create an account or sign in to comment.

Symphony • Open Source XSLT CMS

Server Requirements

  • PHP 5.3-5.6 or 7.0-7.3
  • PHP's LibXML module, with the XSLT extension enabled (--with-xsl)
  • MySQL 5.5 or above
  • An Apache or Litespeed webserver
  • Apache's mod_rewrite module or equivalent

Compatible Hosts

Sign in

Login details