XPath Select node from current node value when two attribute names are the same

Can someone help me with this little question that I have.

XML

<MPN> <MTR MSN="AB123456"/> <MTR MSN="AB654321"/> <MTR MSN="AB654322"/> <MTR MSN="AB654323"/> <MTR MSN="AB654324"/> <JOB JobId="136"> <JMR MSN="AB123456"> <JRA DateActionRequiredBy="20090701120012" /> </JMR> <JMR MSN="AB654321"> <JRA DateActionRequiredBy="20090701100010" /> </JMR> </JOB> </MPN> 

I would like to get DateActionRequiredBy from the JRA element, when the parser sits in the MTR element, only one is returned.

I tried.

 ../JOB/JMR[@MSN = @MSN]/JRA/@DateActionRequiredBy 

which returns {Size: [2]} NodeSet , this corresponds to everything related to the @MSN attribute, which effectively matches itself not with the parent.

 ../JOB/JMR[@MSN = ./@MSN]/JRA/@DateActionRequiredBy 

which returns {Size: [2]} NodeSet

I found a solution, but it will require a variable inside each xsl: attribute that does not seem right to me.

 <xsl:variable name="storeMSN" select="@MSN"/> ../JOB/JMR[@MSN = $storeMSN]/JRA/@DateActionRequiredBy 

which returns the 20090701120012 attribute

This is what I need, but there should be an easier way to achieve this, except for the variable for each attribute.

Thanks in advance.

+4
source share
1 answer
 <MPN> <MTR MSN="AB123456"/> <MTR MSN="AB654321"/><!-- current node (ie context node) --> <MTR MSN="AB654322"/> <MTR MSN="AB654323"/> <MTR MSN="AB654324"/> <JOB JobId="136"> <JMR MSN="AB123456"> <JRA DateActionRequiredBy="20090701120012" /> </JMR> <JMR MSN="AB654321"> <JRA DateActionRequiredBy="20090701100010" /><!-- desired node --> </JMR> </JOB> </MPN> 

then you will need to use this XPath:

 ../JOB/JMR[@MSN = current()/@MSN]/JRA/@DateActionRequiredBy 

Note that this will only work in XSLT, as current() is an XSLT function.

You can facilitate the process by adding an XSL key:

 <xsl:key name="kJMR" match="JMR" use="@MSN" /> 

and in XPath:

 key('kJMR', @MSN)/JRA/@DateActionRequiredBy 

An explanation of why your attempts are not working properly. Both

  • ../JOB/JMR[@MSN = @MSN]/JRA/@DateActionRequiredBy
  • ../JOB/JMR[@MSN = ./@MSN]/JRA/@DateActionRequiredBy

compare @MSN with yourself - an operation that can never fail. This way you always get all the possible nodes.

Within a predicate, the XPath context is always the node to which the predicate applies. The current() function is intended to provide you with XSLT context.

+8
source

Source: https://habr.com/ru/post/1302131/


All Articles