2012-09-05 4 views
5

참조 JAXB 구현에서 XmlSeeAlso에 XmlRootElement의 name = value를 사용하게하려면 어떻게해야합니까?XmlSeeAlso 및 XmlRootElement 이름은 무엇입니까?

내가 원하는 효과는 type 속성이 XmlSeeAlso의 실제 클래스 이름이 아닌 name = value를 사용하는 것입니다.

다른 JAXB 구현이 가능합니까?

작은 예 :

많은 노력없이 가능한
@XmlRootElement(name="some_item") 
public class SomeItem{...} 

@XmlSeeAlso({SomeItem.class}) 
public class Resource {...} 

XML: 
<resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="some_item"> 
... 
</resource> 

?

답변

11

소개 @XmlSeeAlso

@XmlSeeAlso 주석의 목적은 당신의 JAXB (JSR-222) 구현이 Resource에 대한 메타 데이터를 처리 할 때 그것은 또한 SomeItem에 대한 메타 데이터를 처리해야한다는 것을 알 수 있도록하는 것입니다 수업. 어떤 사람들은 실수로 그것이 상속 매핑과 관련이 있다고 믿고 있습니다. 왜냐하면 그것이 상속을 가장 자주 사용하는 유스 케이스이기 때문입니다. Java 리플렉션을 사용하여 클래스의 서브 클래스를 판별 할 수 없으므로 @XmlSeeAlso을 사용하여 JAXB 구현에서 서브 클래스에 대한 맵핑도 작성되어야 함을 알립니다.

자원

자바 클래스에 해당 복합 유형 이름이 @XmlType 주석을 통해 공급된다


다음은 당신이 사용 사례를 지원할 수있는 방법의 예입니다.

package forum12288631; 

import javax.xml.bind.annotation.XmlType; 

@XmlType(name="some_item") 
public class Resource { 

} 

데모

루트 요소 이름은 @XmlRootElement 주석에서 올 수 또는 JAXBElement의 인스턴스를 통해 제공 할 수 있습니다. JAXBElement의 인스턴스를 만들고 Object 인스턴스를 보유하고 있음을 나타냅니다. 마샬링 될 때 xsi:type 속성이 출력에 포함됩니다.

package forum12288631; 

import javax.xml.bind.*; 
import javax.xml.namespace.QName; 

public class Demo { 

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

     Resource resource = new Resource(); 
     JAXBElement<Object> jaxbElement = new JAXBElement<Object>(QName.valueOf("resource"), Object.class, resource); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(jaxbElement, System.out); 
    } 

} 

출력

결과 XML은 Resource@XmlType 주석에서 오는 JAXBElementxsi:type 속성의 값에 의해 공급 루트 요소가 있습니다.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="some_item"/>