2011-11-13 4 views
3

JAXB에 대한 질문이 있습니다.키 값 목록에서 속성 키 = 값

Element { 
    String name 
    List<Attribute> attributes; 
} 

Attribute { 
    String key 
    String value 
} 
getter 및 setter와 물론

및 JAXB 대한 XmlRootElement와 : 기본적으로 내가 가지고있는이 두 클래스는.

이에서 생성 된 XML은 다음과 같습니다

<element> 
    <attributes> 
     <key>id</key> 
     <value>1</value> 
    </attributes> 
    <name>My Element</name> 
</element> 

하지만 내가 찾는 것은 더이 같은 것입니다 :

<element id="1"> 
    <name>My Element</name> 
</element> 

특성의 각 인스턴스를 들면, 나는 키를 원하는 = value (속성으로)

이것은 JAXB에서 가능합니까?

감사합니다, 모르 텐

답변

1

나는 그것이 목록으로 작동 할 것이라고 생각하지 않습니다. 그러나

  • 지도
  • @XmlAnyAttribute를 사용하여 대안이

귀하의 예 : 그

@XmlRootElement 
    public static class Element 
    { 
    @XmlElement 
    String    name; 

    @XmlAnyAttribute 
    Map<QName, Object> map; 
    } 

    { 
    // 
    Element element = new Element(); 
    element.name = "a wonderful name"; 
    element.map = new HashMap<QName, Object>(); 
    element.map.put(new QName("id"), "1"); 
    element.map.put(new QName("other"), "2"); 
    } 

결과 :

안부

<?xml version="1.0" encoding="utf-8" standalone="yes"?> 
<element id="1" other="2"> 
    <name>a wonderful name</name> 
</element> 
!

+0

그래, 그렇게 생각해야 해. XmlAdapter를 사용할 수 있기를 바랬지 만, XmlAnyAttribute가 Map 를 필요로하고 내 어댑터에서 반환 된 것을 사용할 수 없기 때문에 트릭을 수행하지 않는 것처럼 보입니다. 나는 속성에 대한 getter가 새로운 AttributeToMapAdapter(), marshal (_attributes) (여기서 _attributes는 속성의 내부 목록 임)을 리턴했다. 감사! – mortenoh