Search code examples
javaxmlxsdxmlbeans

XMLBeans nested complex element instantiation failure


I'm using XMLBeans to generate java objects from a XSD schema. The Schema is in the following structure :

<schema targetNamespace="" xmlns="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified">
    <element name="Father">
        <complexType>
            <all>
                <element name="Son">
                    <complexType>
                        <all>
                            <element name="Target" type="string" />
                        </all>
                    </complexType>
                </element>
            </all>
        </complexType>
    </element>
</schema>

The schema is compiled allright and I'm able to instantiate the Father by:

Father father = Father.Factory.newInstance();

But when I try to perform :

father.getSon().setTarget("Some String");

I get a null pointer exception. When debugging it, I saw that Son is null (hence the exception). All I need is to set the "Target" value, but I couldn't figure a way to do it....

Is there a way to auto-build all the XSD structure? Alternatively, can I instantiate the "Son" manually and then access its "Target"?

Thanks a lot!

O.J


Solution

  • getSon() method allows you to get the existing child called Son. If you're trying to generate a new xml, you have to start with an empty document. Then you should add your elements as you wish before accessing them. Try this code:

    FatherDocument fatherDocument = FatherDocument.Factory.newInstance();
    Father father = fatherDocument.addNewFather();
    Son son = father.addNewSon();
    son.setTarget("Some string");
    StringWriter writer = new StringWriter();
    fatherDocument.save(writer);
    System.out.println(writer.toString());
    

    I've generated this xml:

    <Father><Son><Target>Some string</Target></Son></Father>