Link to home
Start Free TrialLog in
Avatar of dongjinkim
dongjinkimFlag for Canada

asked on

Need help with <xsl:for-each> and Java Collections

Hello,
I am relatively new to XSL and I'm trying to use the <xsl:for-each> tag with my Java Collection to generate a table.
The problem is that although I am generating the correct number of table rows (so it correctly acknowledges the size of the list), none of the columns are being populated with the data from each list element, except the very last one which is a generic toString() output.
Thank you for any help you can provide!

Here is what I wrote in the *.xsl file:

<table>
  <xsl:for-each select="myList/item">
    <tr>
      <td><xsl:value-of select="name"/></td>
      <td><xsl:value-of select="age"/></td>
      <td><xsl:value-of select="."/></td>
    </tr>
  </xsl:for-each>
</table>

This is what the Java code looks like in my Java Struts Form class:

public class MyForm extends ActionForm {
  .....
  List myList;

  public MyForm() {
    myList = new ArrayList();
    myList.add(new Person("Bob", 30));
  }

  public List getMyList() {
    return myList;
  }
  .....
}

Person is defined as follows:

public class Person {
  String name;
  int age;

  public Person(String name, int age) { this.name = name; this.age = age; }
  public String getName() { return name; }
  public int getAge() { return age; }
  public String toString() { return name + ", " + age; }
}
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Try making Person bean-compliant. No-arg ctor, private fields, public setters
Avatar of dongjinkim

ASKER

Thanks for pointing that out.
I apologize for not showing the original code, but I assure you that the original code is bean compliant.
I tried to simplify the code in an effort to make it more readable, but it appears I left out some details.
try:

     <td><xsl:value-of select="@name"/></td>
      <td><xsl:value-of select="@age"/></td>
Hi

In this blog http://vivekthangaswamy.blogspot.com/2006/09/xml-and-xslt-transformation-using-cnet.html
you can find a source code attached, in that source code file you can find a XSLT in that XSLT thr are lots of Recursive functions and loops are done. It will be more helpfull for you. And you can find very good examples for for-each in XSL try out...
I found out how to access the member methods of Person.
I had to change the XML as follow:

From:
  <xsl:for-each select="myList/item">
To:
  <xsl:for-each select="myList/Person">

I also had to override the HttpServlet's service method to handle the Person class.
ASKER CERTIFIED SOLUTION
Avatar of Computer101
Computer101
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial