Search code examples
xpathhierarchy

xpath hierarchy by element sequence


I have the following problem:

<root>
<b>Value 1</b>
<p>item 1</p>
<p>item 2</p>
<p>item 3</p>

<b>Value 2</b>
<p>item 1</p>
<p>item 2</p>

<b>value 3</b>
<p>item 1</p>
<p>item 2</p>
<p>item 3</p>
<p>item 4</p>
</root>

I would like to have an XPath expression that allow me to extract the values in following way:

  Value 1 - item 1
  Value 1 - item 2
  Value 1 - item 3
  Value 2 - item 1
  Value 2 - item 2
  Value 3 - item 1
  Value 3 - item 2
  Value 3 - item 3
  Value 3 - item 4

Is it possible ?


Solution

  • If you are using xslt then this should provide some insight basicly select the

    elements and individually then find the first preceeding element

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    
        <xsl:template match="/">
            <xsl:apply-templates select="//p"/>
        </xsl:template>
    
        <xsl:template match="p">
             <xsl:value-of select="preceding::b[1]"/> <xsl:value-of select="."/>
        </xsl:template>
    
    </xsl:stylesheet>