Search code examples
xmlbeans

Can I get an XmlObject instance if I have its corresponding SchemaType object?


In XmlBeans, I have a compiled schema and I create an instance through the

MyStuff stuff = MyStuff.Factory.newInstance() method.

But in a part of my application I need to treat MyStuff as a generic XmlObject and yet I want to create instances of it. Suppose that I want to do:

workWithObjectsAbstractly(stuff)

where workWithObjectsAbstractly is defined as:

public void workWithObjectsAbstractly(XmlObject o)
{
  .
  .
   SchemaType type = o.schemaType();
   XmlObject newInstance = type.???????   <--- is there such method?
  .
  .
  [Work with new instances as XmlObjects]
  . 
} 

Is there a way to do that? I could inspect the schemaType through Particles and Properties and then create stuff with XmlCursor, but it seems cumbersome. Can I avoid it?


Solution

  • I don't think you can avoid this, org.apache.xmlbeans.impl.xsd2inst.XmlSampleUtil does this abstraction in order to create auto-generated, valid instances from a SchemaType.

    In this case, it uses

    XmlObject object = XmlObject.Factory.newInstance();
    XmlCursor cursor = object.newCursor();
    // Skip the document node
    cursor.toNextToken();
    // ... it then uses the cursor to add elements, attributes, etc
    

    Hope that helps a bit...