在 XSD 模式中如何对具有不同名称和一种基本类型的元素进行序列?
<function name="test">
<set name="name" value="StackMommy" />
<log message="hello, ${name}" />
</function>
我想要用 jaxb 生成 pojo 类:
class Function {
List<Command> commands;
}
最佳答案
@XmlElementRef
注释就是您在此用例中寻找的内容。它用于映射替换组的概念。
函数
commands
属性使用 @XmlElementRef
进行注释。这意味着我们将根据出现的 XML 元素填充此属性,这些元素通过 @XmlRootElement
或 @XmlElementDecl
与 Command
的子类关联。
package forum9952449;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
class Function {
@XmlElementRef
List<Command> commands;
}
命令
@XmlSeeAlso
注释用于指向子类。这不是必要的步骤,但它确实意味着我们在引导 JAXBContext
时不必显式传递子类。
package forum9952449;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlSeeAlso({Set.class, Log.class})
public abstract class Command {
}
设置
我们需要使用@XmlRootElement
来注释这个类。在这种情况下,根元素名称默认为 set
。
package forum9952449;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Set extends Command {
@XmlAttribute
private String name;
@XmlAttribute
private String value;
}
日志
我们再次用@XmlRootElement
注释这个子类。
package forum9952449;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Log extends Command {
@XmlAttribute
private String message;
}
演示
package forum9952449;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Function.class);
File xml = new File("src/forum9952449/input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Function function = (Function) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(function, System.out);
}
}
输入/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<function>
<set value="StackMommy" name="name"/>
<log message="hello, ${name}"/>
</function>
函数.xsd
相应的 XML 架构如下所示。由于您可以使用 JAXB 从对象模型开始,因此您并不真正需要它。
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="function" type="function"/>
<xs:element name="command" type="command"/>
<xs:element name="set" type="set"
substitutionGroup="command"/>
<xs:element name="log" type="log"
substitutionGroup="command"/>
<xs:complexType name="function">
<xs:sequence>
<xs:element ref="command"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="command" abstract="true">
<xs:sequence/>
</xs:complexType>
<xs:complexType name="set">
<xs:complexContent>
<xs:extension base="command">
<xs:attribute name="name" type="xs:string"/>
<xs:attribute name="value" type="xs:string"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="log">
<xs:complexContent>
<xs:extension base="command">
<xs:attribute name="message"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:schema>
了解更多信息
关于java - 具有基本类型的 XSD 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9952449/