How to get Digester handle recursive childnodes?
Hello!I try to get a grip of Digetser from apache.
But I can get it to handle recursive childnodes.
If you try the code below. You will se this output:
--- Elements ---
--- attributes ---
Element: =o'1'
--- attributes ---
Element: =o'2'
--- attributes ---
Element: =o'3'
--- attributes ---
Element: =o'4'
--- attributes ---
Element: =o'6'
If you uncomment the //Add Child Elements recusive - part it do not handles the child nodes.
If you have any idea how to get Digester to get the childnodes as well please let me know.
I can not figure it out.
Best regards
Fredrik
<?xml version="1.0" encoding="UTF-8" ?>
<data>
<e o="0">
<e o="1"/>
<e o="2"/>
<e o="3"/>
<e o="4">
<e o="5"/>
</e>
<e o="6"/>
</e>
</data>
package digestertester;
import org.apache.commons.digester.*;
import java.io.File;
import java.util.Vector;
public class ElementDigester {
public static void main( String[] args ) {
try {
Digester digester = new Digester();
digester.setValidating( false );
digester.setRules(new ExtendedBaseRules());
digester.addObjectCreate( "data", Data.class );
digester.addObjectCreate( "data/e/e", Element.class );
digester.addSetProperties( "data/e/e", "o", "o" );
//Add Child Elements recusive
//digester.addObjectCreate( "!*/e/e", Element.class );
//digester.addSetProperties( "!*/e/e", "o", "o" );
//digester.addSetNext( "!*/e/e", "addChildElement" );
digester.addSetNext( "data/e/e", "addElement" );
File input = new File( "D:/Fredrik/Javalabb/digestertester/xml/4.xml" );
Data data = (Data)digester.parse( input );
System.out.println( data.toString() );
} catch( Exception exc ) {
exc.printStackTrace();
}
}
}
package digestertester;
import java.util.Vector;
public class Data
{
private Vector elements;
public Data()
{
elements = new Vector();
}
public void addElement(Element element) {
elements.add(element);
}
public String toString() {
String newline = System.getProperty( "line.separator" );
StringBuffer buf = new StringBuffer();
buf.append( "--- Elements ---" ).append( newline );
for( int i=0; i<elements.size(); i++ ){
buf.append( elements.elementAt(i) ).append( newline );
}
return buf.toString();
}
}
package digestertester;
import java.util.Vector;
public class Element {
private String o;
private Vector childElements;
public Element() {childElements = new Vector();}
public void setO( String o ) { this.o = o; }
public void addChildElement( Element element ) {
childElements.addElement( element );
}
public String toString() {
String newline = System.getProperty( "line.separator" );
StringBuffer buf = new StringBuffer();
buf.append( "--- attributes ---" ).append( newline );
buf.append( "\t\tElement: =o'" + o + "'").append( newline );
if(childElements.size() > 0)
{
buf.append( "--- childelements ---" ).append( newline );
for( int i=0; i<childElements.size(); i++ ){
buf.append( childElements.elementAt(i) ).append( newline );
}
}
return buf.toString();
}
}
