的@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