JAXB为没有内容的标签设置了一个值。

时间:2022-11-19 14:43:56

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:

我正在使用JAXB从XML模式生成一个bean模型。模式中的一个结构是某个标记是否存在。例如在下面的狙击声中:

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

In the XSD I've mapped this as:

在XSD中,我将其映射为:

<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:

在由JAXB生成的BuildtimeBehavior类中,这导致:

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...

现在我想要设置或清除那个标签。但是,我不能简单地执行“new Object()”,因为这会导致“java.lang”。对象不能被强制转换为org.w3c.dom.Element"。但是我没有创建元素的文档。由JAXB生成的ObjectFactory没有一个createPing()方法……

How do I set ping?

如何设置ping?

1 个解决方案

#1


0  

You could create the ping element as follows:

您可以创建如下所示的ping元素:

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.

在您的问题中,您声明您是从XML模式生成模型的。如果您可以修改模型或从Java类开始,下面是可以使用XmlAdapter尝试的方法的链接。

#1


0  

You could create the ping element as follows:

您可以创建如下所示的ping元素:

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.

在您的问题中,您声明您是从XML模式生成模型的。如果您可以修改模型或从Java类开始,下面是可以使用XmlAdapter尝试的方法的链接。