XMLBeans嵌套了复杂元素实例化失败

时间:2011-03-22 17:59:31

标签: java xml xsd xmlbeans

我正在使用XMLBeans从XSD架构生成java对象。 Schema具有以下结构:

<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>

架构编译得很好,我可以通过以下方式实例化父

Father father = Father.Factory.newInstance();

但是当我尝试表演时:

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

我得到一个空指针异常。在调试它时,我看到Son是null(因此是例外)。 我只需要设置“目标”值,但我无法想办法......

有没有办法自动构建所有XSD结构?或者,我可以手动实例化“Son”然后访问其“Target”吗?

非常感谢!

O.J

1 个答案:

答案 0 :(得分:0)

getSon()方法允许您获取名为Son的现有子项。如果您正在尝试生成新的xml,则必须从空文档开始。然后,您应该在访问它们之前添加您想要的元素。 试试这段代码:

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());

我已经生成了这个xml:

<Father><Son><Target>Some string</Target></Son></Father>
相关问题