gpt4 book ai didi

jaxb - 相当于 EclipseLink MOXy 中 @XmlPath 中的 @XmlElement.required

转载 作者:行者123 更新时间:2023-12-04 16:50:30 24 4
gpt4 key购买 nike

如何在EclipseLink MOXy 中使用@XmlPath 注释实现@XmlElement.required 标志| 2.4.1版本?

最佳答案

您可以使用 @XmlElement(required=true)@XmlPath 注释来指定叶元素是必需的。

客户

下面是一个示例域模型,其中两个字段用 @XmlPath 映射,其中一个字段我还使用了 @XmlElement(required=true)

package forum13854920;

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

@XmlPath("personal-info/first-name/text()")
private String firstName;

@XmlPath("personal-info/last-name/text()")
@XmlElement(required=true)
private String lastName;

}

jaxb.properties

要将 MOXy 用作您的 JAXB 提供程序,您需要在与域模型相同的包中包含一个名为 jaxb.properties 的文件,其中包含以下条目:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

XML 架构

下面是领域模型对应的XML schema。注意 last-name 元素没有 minOccurs="0"

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:complexType name="customer">
<xsd:sequence>
<xsd:element name="personal-info" minOccurs="0">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="first-name" type="xsd:string" minOccurs="0"/>
<xsd:element name="last-name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>

演示

以下演示代码可用于生成 XML 架构。

package forum13854920;

import java.io.IOException;
import javax.xml.bind.*;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);

jc.generateSchema(new SchemaOutputResolver() {

@Override
public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
StreamResult result = new StreamResult(System.out);
result.setSystemId(suggestedFileName);
return result;
}

});
}

}

当前 EclipseLink JAXB (MOXy)对于路径的其他段,在 @XmlElement 注释上没有等效的 required 属性。如果您对此行为感兴趣,请使用以下链接输入增强请求:

关于jaxb - 相当于 EclipseLink MOXy 中 @XmlPath 中的 @XmlElement.required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13854920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com