I have created an XML schema for my webservice, and the element for ServerResponse contains an unbounded sequence of elements of type xs:any.
I am generating classes (using xjc) from my schema, and so this sequence is converted to List in the generated ServerResponse class.
The ServerResponse class has a method, getAny(), which returns this List and allows me to make changes to it.. but I can't figure out exactly how to do this.
Say I want to add a couple of elements to the sequence of any objects in the response, so that the XML of the response will contain this.
<someelement1>sometext</someelement1>
<someelement2>somemoretext</someelement2>
from the Java server side code, how would I add these two elements to the getAny() object? I thought it could be done something like this:
Object element = new Object();
((Element)element).setNodeValue("someelement1");
((Element)element).setTextContent("sometext");
requestobject.getAny().add(element);
However this doesn't work, as it throws an error stating that "java.开发者_开发技巧lang.object cannot be cast to org.w3.dom.Element".
Can anyone help me do this? I'm sure there's a pretty simple solution!
Thanks for any help :)
Object
does not implement Element
, so this cast will always fail.
You can create Element
instances using a DocumentBuilder
which you can get from a DocumentBuilderFactory
.
Here is some sample JAXB code:
@XmlRootElement
public class Anything {
private Object any;
@XmlAnyElement
public Object getAny() { return any; }
public void setAny(Object any) { this.any = any; }
public static void main(String[] args) throws DOMException,
ParserConfigurationException {
Element foo = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.newDocument()
.createElement("foo");
Anything a = new Anything();
a.setAny(foo);
JAXB.marshal(a, System.out);
}
}
I haven't tried this under JAX-WS (JAX-WS uses JAXB bindings) - if it doesn't work, I'd start digging round the javax.xml.soap package.
精彩评论