I am working on a webservices client application, and I mainly work. I can get and read data from a third-party web service. Now I need to submit some data, and I'm stuck.
The classes for the objects I receive / send were generated from XSD files using the xjc tool. The part I'm stuck on turns one of these objects into an XML tree to send to a web service.
When I receive / send a request from / to ws, it contains a payload object. This is defined in java code as (partial list):
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PayloadType", propOrder = { "compressed", "document", "any", "format" }) public class PayloadType { @XmlElement(name = "Compressed") protected String compressed; @XmlElement(name = "Document") protected List<String> document; @XmlAnyElement protected List<Element> any; protected String format; public List<Element> getAny() { if (any == null) { any = new ArrayList<Element>(); } return this.any; } }
The only field I'm associated with is the "any" field, which contains an XML tree. When I retrieve data from ws, I read this field with something like this: ("root" is of type org.w3c.dom.Element and is the result of calling getAny (). Get (0) on the payload object)
NodeList nl = root.getElementsByTagName("ns1:Process"); // "ns1:Process" is an XML node to do something with if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { Element proc = (Element) nl.item(i); try { // do something with the 'proc' Element here... } catch (Exception ex) { // handle problems here... } } }
Sending data is where I got stuck. How to take a java object created from one of the classes generated from XSD and turn it into an Element object, which I can add to the βanyβ list of the payload object? For example, if I have a DailyData class, and I create and populate it with data:
DailyData dData = new DailyData(); dData.setID = 34; dData.setValues = "3,5,76,23";
How to add this dData object to the "any" list of the payload object? It must be an Element. Am I doing something with the JAXBContext marshaller? I used this to dump the dData object on the screen to check the XML structure.
I'm sure the answer is looking in my face, but I just don't see it!
Dave
UPDATE: working with the code snippet below:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc = dbf.newDocumentBuilder().newDocument(); JAXBContext context = JAXBContext.newInstance(DailyData.class); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(dData, doc); PayloadType payload = new PayloadType(); payload.getAny().add((Element)doc.getFirstChild());