这是像No @XmlRootElement generated by JAXB这样的问题的相反方向。基本上,我想运行schemagen,并拥有两个相同类型的全局元素。
<xs:element name="root1" type="tns:sameType"/>
<xs:element name="root2" type="tns:sameType"/>我知道如何使用JAXBElement编组数据,但是我不知道如何正确地生成模式。在我看来,它看起来像下面的代码片段(@XmlRootElements是虚构的)。
@XmlRootElements(value = {
@XmlRootElement(name="root1", namespace="urn:example"),
@XmlRootElement(name="root2", namespace="urn:example")
})发布于 2013-02-13 09:38:05
您可以在带有@XmlRegistry注释的类上使用@XmlElementDecl注释。
ObjectFactory
当一个类型有多个全局元素与之对应时,将使用@XmlElementDecl注释。注释被放在用@XmlRegistry注释的类上的create方法上。当从XML schema生成模型时,这个类总是被称为ObjectFactory。
package forum14845035;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRegistry
public class ObjectFactory {
@XmlElementDecl(name="root1")
public JAXBElement<SameType> createRoot1(SameType sameType) {
return new JAXBElement<SameType>(new QName("urn:example", "root1"), SameType.class, sameType);
}
@XmlElementDecl(name="root2")
public JAXBElement<SameType> createRoot2(SameType sameType) {
return new JAXBElement<SameType>(new QName("urn:example", "root2"), SameType.class, sameType);
}
}SameType
在这个用例中,域类上不需要注释。
package forum14845035;
public class SameType {
}package-info
我们将利用包级@XmlSchema注释来为我们的模型指定名称空间限定。
@XmlSchema(namespace="urn:example", elementFormDefault=XmlNsForm.QUALIFIED)
package forum14845035;
import javax.xml.bind.annotation.*;演示
package forum14845035;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.SchemaOutputResolver;
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(SameType.class, ObjectFactory.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;
}
});
}
}输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema elementFormDefault="qualified" version="1.0" targetNamespace="urn:example" xmlns:tns="urn:example" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root1" type="tns:sameType"/>
<xs:element name="root2" type="tns:sameType"/>
<xs:complexType name="sameType">
<xs:sequence/>
</xs:complexType>
</xs:schema>有关详细信息的,请访问
https://stackoverflow.com/questions/14845035
复制相似问题