Java 클래스에서 모든 속성을 저장할 수있게하려면 속성 이름/값 쌍을 저장하려면 Map
이 필요하고 해당 필드에 @XmlAnyAttribute
으로 주석을 추가해야합니다.
@XmlRootElement(name = "field")
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
@XmlAttribute(name="attribute1")
String attribute1;
@XmlAttribute(name="attribute2")
String attribute2;
@XmlAttribute(name="attribute3")
String attribute3;
@XmlAnyAttribute
Map<String, String> attributes;
}
테스트 당신이 볼 수 있듯이, 두 개의 "추가"속성이 추가되었습니다
String xml = "<field attribute1=\"A\"" +
" attribute2=\"B\"" +
" attribute3=\"C\"" +
" attribute4=\"D\"" +
" foo=\"Bar\" />";
JAXBContext jaxbContext = JAXBContext.newInstance(Field.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Field field = (Field) unmarshaller.unmarshal(new StringReader(xml));
System.out.println("field.attribute1 = " + field.attribute1);
System.out.println("field.attribute2 = " + field.attribute2);
System.out.println("field.attribute3 = " + field.attribute3);
System.out.println("field.attributes = " + field.attributes);
출력
field.attribute1 = A
field.attribute2 = B
field.attribute3 = C
field.attributes = {attribute4=D, foo=Bar}
: 여기
은 예제 코드입니다 지도.
당신이 xml = "<field/>";
로 즉 동일한 테스트하지만, 어떤 속성없이를 실행하면, 당신이 얻을 :
field.attribute1 = null
field.attribute2 = null
field.attribute3 = null
field.attributes = null
attributes
필드가 할당되지 않은 남아 즉 null
. 빈지도가 아닙니다.
은 저에게 매우 효과적입니다. – raccoon