Handling <xs:any> with XML Beans
This article explains how to add an XmlObject to another XmlObject. In this case, the parent XmlObject has children of type <xs:any>. The tricky part is that XML Beans does not create accessor methods for
<xs:any>
elements.
In my case, I was creating a SOAP response. Here’s the snippet that creates a SOAP fault:
// SOAP schema XML Bean imports import org.xmlsoap.schemas.soap.envelope.Body; import org.xmlsoap.schemas.soap.envelope.Detail; import org.xmlsoap.schemas.soap.envelope.Envelope; import org.xmlsoap.schemas.soap.envelope.EnvelopeDocument; import org.xmlsoap.schemas.soap.envelope.Fault; import org.xmlsoap.schemas.soap.envelope.FaultDocument; import org.xmlsoap.schemas.soap.envelope.Header; // DOM Imports import org.w3c.dom.Element; import org.w3c.dom.Node;... now the real code // the XML document looks like this: <envelope> <body> <fault> ... </fault> </body> <envelope> // create envelope and body EnvelopeDocument responseEnv = EnvelopeDocument.Factory.newInstance(); Body responseBody = responseEnv.addNewEnvelope().addNewBody(); // create fault, must be a FaultTDocument. If you just create a // Fault instance, it will be an an XML fragment, nothing will work FaultDocument faultDoc = FaultDocument.Factory.newInstance(); Fault fault = faultDoc.addNewFault(); fault.setFaultcode(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Client")); ... some more code that populates the fault object // now the tricky part Node bodyNode = responseBody.getDomNode(); importedNode = bodyNode.getOwnerDocument().importNode(faultDoc.getFault().getDomNode(), true); bodyNode.appendChild(importedNode);
The tricky part is the last 3 lines of code, I used the DOM API, not the XML Beans API, to add an XmlObject instance as a child of another XmlObject instance. Also, make sure that the node you import comes from an element that is part of a document, not just a parent-less XmlObject instance (it would be one of those useless XML fragments, frankly that part of the API is counterintuitive.)