2

I'm using JAXB to generate a bean model from a XML schema. One of the constructs in the schema is that a certain tag can be present or not. For example the ping in the sniplet below:

   <buildtime-behavior>
        <ping/>
    </buildtime-behavior>

In the XSD I've mapped this as:

<xs:element name="buildtime-behavior">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="ping" minOccurs="0" maxOccurs="1"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

And in the by JAXB generated BuildtimeBehavior class this results in:

public void setPing(Object value) 

Now I want to set or clear that tag. However I cannot simply do a "new Object()" because that will result in a "java.lang.Object cannot be cast to org.w3c.dom.Element". But I have no Document to create a Element. The by JAXB generated ObjectFactory does not have a createPing() method...

How do I set ping?

tbeernot
  • 2,473
  • 4
  • 24
  • 31
  • This might answer your question: http://stackoverflow.com/questions/594537/how-to-instantiate-an-empty-element-with-jaxb – John Farrelly Apr 24 '12 at 09:31

1 Answers1

0

You could create the ping element as follows:

package forum10294935;

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Element pingElement = document.createElement("ping");
    }

}

In your question you stated that you generated your model from an XML schema. If you can modify your model or start from Java classes, below is a link to an approach you can try using an XmlAdapter.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • An alternative is to parse an XML with the ping set and get the value from the getter. Object lPing = lJAXBWithPingSet.getBuildtimeBehavior().getPing(); lMyJAXB.getBuildtimeBehavior().setPing(lPing); – tbeernot Apr 24 '12 at 09:42