Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath filtering sub node

Tags:

xml

xpath

I have a xml contains following information, i am using Xpath to parse the it

<root>
  <a>
    <b></b>
    <c></c>
    <d></d>
  </a>
  <a>
    <b></b>
    <c></c>
    <d></d>
  </a>
</root>

my target is to get the nodelist of tag 'a' and in each sub nodelist containing 'b' and 'c' (etc. filter out 'd'!) what I am currently doing is use '/root/a' to get nodes containing all 'a','b' and 'c', then get rid of 'c' afterwards, what I am targeting to do it do the filtering within XPath instead of using extra code, is there anyway I can do it? thanks!

like image 482
user1409920 Avatar asked Jun 18 '26 19:06

user1409920


1 Answers

You can filter out an element by copy everything with the pattern below and just intercept the elements you want to filter out.

<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">


  <xsl:template match="a/d"/>


  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet> 

This works because special templates have a higher priority over general templates. So the second one applies to all elements except for d below a. The first template just does nothing, i.e. ignores the element.

like image 132
topskip Avatar answered Jun 21 '26 11:06

topskip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!