具有基本类型的XSD元素
问题描述:
XSD模式如何在具有不同名称和基本类型的元素中执行序列?具有基本类型的XSD元素
<function name="test">
<set name="name" value="StackMommy" />
<log message="hello, ${name}" />
</function>
我想和JAXB生成的POJO类的一些这样的:
class Function {
List<Command> commands;
}
答
的@XmlElementRef
注解是你在找什么在这个用例。它用于映射替代组的概念。
功能
的commands
属性注解与@XmlElementRef
。这意味着我们将根据出现的与Command
的子类关联的XML元素,通过@XmlRootElement
或@XmlElementDecl
来填充此属性。
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>
function.xsd
相应的XML舍姆a看起来像下面这样。正如您可以从使用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>
更多信息
http://jaxb.java.net/guide/Mapping_interfaces.html可能的帮助。 – Barend 2012-03-31 07:44:18