Search code examples
xmlxsltforeachiteration

Taking the value of the node above in xsl for-each loop


Given the following XML format:

<Book>
  <ID>160-2<ID>
  <Author>
    <Name>Mark Polo</Name>
  </Author>
  <Cost>
     <Shop>BookLover</Shop>
     <Value>2000</Value>
  </Cost>
  <Cost>
     <Shop>MakingBooks</Shop>
     <Value>1500</Value>
  </Cost>
  <Cost>
     <Shop>AppleBooks</Shop>
     <Value>3000</Value>
  </Cost>
</Book>

Need to make following structure:

<BookCost>
  <ID>160-2</ID>
  <AuthorName>Mark Polo</AuthorName>
  <Value>2000</Value>
</BookCost>
<BookCost>
  <ID>160-2</ID>
  <AuthorName>Mark Polo</AuthorName>
  <Value>1500</Value>
</BookCost>
<BookCost>
  <ID>160-2</ID>
  <AuthorName>Mark Polo</AuthorName>
  <Value>3000</Value>
</BookCost>

Element Book and Cost are unbounded. I guess I should go into the loop xsl:for-each select="Cost", but is there any possible way to get ID and shop name, if if the number of Book and Cost elements is multiple and unknown? Here is the example of xslt:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
        <xsl:template match="/">
        <resultDocument>
        <xsl:for-each select="//document/Book/Cost">
        <BookCost>
        <ID>??</ID>
        <AuthorName>??</AuthorName>
        <Value>
        <xsl:value-of select="Value"/>
        </Value>
        </BookCost>
        </xsl:for-each>
        </resultDocument>
        </xsl:template>
</xsl:stylesheet>

Solution

  • Moving comment to answer...

    If you select Cost in an xsl:for-each, you can get the ID and author name by going back up the tree using .. (which selects the parent and is abbreviated syntax for parent::*).

    Examples:

    ../ID

    and

    ../Author/Name