Home > OS >  I need help traversing some XML using XLST and extracting the data
I need help traversing some XML using XLST and extracting the data

Time:10-07

I have some XML and am required to extract the data using XLST. I need to pull out the data in pairs via Name, Description with their respective values for output in XLST.

So..

txt_name, Jonathan Smith

txt_description, Man


txt_name, Mary Smith

txt_description, Woman


Here is the XML.

<?xml version="1.0" encoding="UTF-8"?>
<dfor:form-data xmlns:dfor="http://kana.com/dforms">
    <dfor:field>
        <dfor:name>eml_email</dfor:name>
        <dfor:value>[email protected]</dfor:value>
    </dfor:field>
    <dfor:field>
        <dfor:name>otom_children</dfor:name>
        <dfor:children>
            <dfor:child>
                <dfor:field>
                    <dfor:name>txt_name</dfor:name>
                    <dfor:value>Mary Smith</dfor:value>
                </dfor:field>
                <dfor:field>
                    <dfor:name>txt_description</dfor:name>
                    <dfor:value>Woman</dfor:value>
                </dfor:field>
            </dfor:child>
            <dfor:child>
                <dfor:field>
                    <dfor:name>txt_name</dfor:name>
                    <dfor:value>Jonathan Smith</dfor:value>
                </dfor:field>
                <dfor:field>
                    <dfor:name>txt_description</dfor:name>
                    <dfor:value>Man</dfor:value>
                </dfor:field>
            </dfor:child>
        </dfor:children>
    </dfor:field>
</dfor:form-data>

I have tried traversing using "<xsl:for-each select=" but am unable to get it working.

CodePudding user response:

Try:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:dfor="http://kana.com/dforms">

  <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>

  <xsl:template match="/">
    <xsl:for-each select="//dfor:child"><!-- outer loop -->
      <xsl:for-each select="dfor:field"><!-- inner loop -->
        <xsl:value-of select="dfor:name"/>
        <xsl:text>, </xsl:text>
        <xsl:value-of select="dfor:value"/>
        <xsl:text><!-- output new line -->
</xsl:text>
      </xsl:for-each>
      <xsl:text><!-- output 1 extra new line after the inner loop -->
</xsl:text>    
  </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>
  • Related