Here's an integrated test case:
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
public class XStreamTest {
public static void main(String[] args) {
XStream xs = new XStream();
xs.registerConverter(new TestConverter());
TestClass test = new TestClass();
//change to true to see the problem
boolean bug = false;
if (bug)
{
test.value = "";
}
else
{
test.value = "some text";
}
test.children.add("one");
test.children.add("two");
try
{
FileWriter out = new FileWriter("test.xml");
xs.toXML(test, out);
out.close();
FileReader in = new FileReader("test.xml");
xs.fromXML(in);
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static class TestConverter implements Converter {
public boolean canConvert(Class cls)
{
return TestClass.class.equals(cls);
}
public void marshal(Object obj, HierarchicalStreamWriter writer, MarshallingContext context)
{
TestClass test = (TestClass) obj;
writer.setValue(test.value);
context.convertAnother(test.children);
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
TestClass test = new TestClass();
//in 'bug mode' reader.hadMoreChildren() will return false the first time
test.value = reader.getValue();
//Uncomment the lines below to get an exception for both values of 'bug' above
//test.value = reader.getValue();
//test.value = reader.getValue();
//test.value = reader.getValue();
while (reader.hasMoreChildren())
{
reader.moveDown();
System.out.println(reader.getNodeName());
reader.moveUp();
}
return test;
}
}
public static class TestClass
{
public String value;
public List children = new LinkedList();
}
}
Could you provide some sample XML for this.
thanks
-Joe