I've decided to use JAXB in my web app as I've used it before (2 years ago). Before I started working on this web app, I upgraded to jdk1.6.0_07 with JAXB included and I'm using Netbeans 6.1 as my IDE.
I've got a very simple scenario in one Main.java that I can't get to the bottom of. I want to be able to unmarshal an XML file into a set of java objects and traverse through the object tree. I can get access to the root node of my XML structure. However, I keep failing to get the 2nd level of the hierarchy. I get an error about being unable to cast to com.sun.org.apache.xerces.internal.dom.ElementNSImpl (java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to generated.HierType
at javaapplication1.Main.main(Main.java:41)
Any help on how to traverse a tree would be greatly appreciated.
Here's my source code:
=======================================================
public class Main
{
public static void main(String[] args)
{
System.out.println("hello world!");
try
{
JAXBContext jc = JAXBContext.newInstance("generated");
Unmarshaller u = jc.createUnmarshaller();
File f = new File("document_list.xml");
JAXBElement<?> hierElement = (JAXBElement<?>)u.unmarshal(new FileInputStream(f));
HierType hierType = (HierType)hierElement.getValue();
System.out.println("Root name : " + hierType.getName());
ListIterator iter = hierType.getHier().listIterator();
while(iter.hasNext())
{
HierType o = (HierType)iter.next();
System.out.println(o.getName());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
=======================================================
Here's the XML
=======================================================
<?xml version="1.0" encoding="UTF-8"?>
<hier name="Document Root">
<hier name="level1">
<hier name="level1.1">
</hier>
</hier>
<hier name="level2">
</hier>
<hier name="level3">
</hier>
</hier>
=======================================================
Here's the XSD
=======================================================
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="hier" type="HierType"/>
<xsd:complexType name="HierType">
<xsd:sequence>
<xsd:element name="hier" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>