Nested For Loops

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gaurav87
    New Member
    • Jul 2008
    • 1

    Nested For Loops

    This is a small part the xml file that I have:

    <Prop Type='TEResult' Flags='0x0'>
    <Prop Name='Status' Type='String' Flags='0x400000 '>

    <Value>Done</Value>

    </Prop>
    <Prop Name='StepName' Type='String' Flags='0x0'>

    <Value>Scan CPU Serial Number</Value>

    </Prop>
    </Prop>

    Now this small xml code repeats numerously throughout my xml file.I want to go through the entire xml file and extract the values (which are Done and Scan CPU Serial Number in this case) of all Prop with Name='Status' and Name='StepName' .

    My output needs to look like this

    <TestName>Sca n CPU Serial Number</TestName>
    <TestResult>Don e</TestResult>

    I am using nested for each statements and this is the output it is giving me:
    <TestName>Sca n CPU Serial Number>
    <TestResult>Don e</TestResult>
    <TestResult>Don e</TestResult> (2)
    <TestResult>Don e</TestResult>
    <TestResult>Don e</TestResult>
    <TestResult>Don e</TestResult>
    <TestResult>Don e</TestResult>
    <TestResult>Don e</TestResult>
    <TestResult>Don e</TestResult>
    <TestResult>Don e</TestResult>
    <TestName><Th is is the next test></TestName>

    What essentially should be happening is that Result( 2) should come below my next <TestName> but because of my nested for each loops, it goes through the entire xml file, prints all the results and then goes back to the next test, then again all the results instead of <Test><Its Result> <Test><Its Result>?

    How can I solve this?
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    It'd be easier if we could see your code, but it'd probably be something like:

    [code=xml]
    <xsl:template match="Prop">
    <xsl:choose>
    <xsl:when test="@Name = 'StepName'">
    <TestName><xsl: value-of select="Value"/></TestName>
    </xsl:when>
    <xsl:when test="@Name = 'Status'">
    <TestResult><xs l:value-of select="Value"/></TestResult>
    </xsl:when>
    </xsl:choose>
    </xsl:template>
    [/code]

    Use an apply-templates, instead of a for-each loop.
    You haven't nested the results inside a step node, so you can't use for-each like that either.

    If you really want to, or are changing your code to become proper structured xml (eg, where your steps are grouped together under one node) you could use a key.

    [code=xml]
    <xsl:key name="StepName" match="Prop" select="precedi ng-sibling::Prop[@Name='StepName '][1]"/>

    <xsl:for-each select="Prop[@Name = 'StepName']>
    Put test name here.
    <xsl:for-each select="key('St epName', .)">
    Test Values here.
    </xsl:for-each>
    </xsl:for-each>
    [/code]

    Comment

    Working...