|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
more xpath Help needed
I am currently searching various xpath tutorials in order to try and figure this out, but wanted to post it here as well to see if someone could help me out.
Say I have the following xml document: <AAA> <BBB elementID="1234"> <CCC string= "asdf"/> </BBB> <GGG elementID="5678"> <DDD/> <EEE> <FFF string="hjkl"/> </EEE> </GGG> <HHH> <III/> </HHH> </AAA> What I am trying to do is...anywhere there is a "string" select it AND the preceding "elementID" that goes with it. A string will always have an element ID preceding it. After selecting I willprint them on a line in this fashion. elementID1value, stringvalue1 elementID2value, stringvalue2 etc. The trick is that the "string" can be embedded one level or many levels. Any suggestions? |
|
#2
|
||||
|
||||
|
Solution
Does anyone have another solution?
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:call-template name="printPairs"> <xsl:with-param name="startNode" select="/"/> </xsl:call-template> </xsl:template> <xsl:template name="printPairs"> <xsl:param name="startNode"/> <xsl:param name="mostRecentElementId"/> <xsl:if test="@string"> <xsl:value-of select="$mostRecentElementId"/> <xsl:text>, </xsl:text> <xsl:value-of select="$startNode/@string"/> <xsl:text> </xsl:text> </xsl:if> <xsl:for-each select="$startNode/child::node()"> <xsl:choose> <xsl:when test="@elementID"> <xsl:call-template name="printPairs"> <xsl:with-param name="startNode" select="."/> <xsl:with-param name="mostRecentElementId" select="@elementID"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name="printPairs"> <xsl:with-param name="startNode" select="."/> <xsl:with-param name="mostRecentElementId" select="$mostRecentElementId"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:for-each> </xsl:template> </xsl:stylesheet> |
|
#3
|
|||
|
|||
|
> Does anyone have another solution?
I think your solution is as good as it gets - F |
|
#4
|
|||
|
|||
|
Well, I don't know that this is any better, but it should be shorter at least.
"//.[boolean(@string)]" will give you all the nodes with a string attribute. "./ancestor::node()[boolean(@elementID)]" will give you all the parent nodes of the current node that have elementID attributes. This works great if you don't have nested elementID nodes, otherwise you have to loop through the node-set to get the last() node. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages - More > XML Programming > more xpath Help needed |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|