2010-02-23 7 views

Répondre

-1

Vous pouvez utiliser XPath.

Son très rapide sur les JVM modernes et une compétence transférable. Par exemple. vous pouvez utiliser XPath sur .NET etc

0

En fait, il y a une réponse sur le site XStream - dans le tutoriel Converter;)

De http://x-stream.github.io/converter-tutorial.html:

public Object unmarshal(HierarchicalStreamReader reader, 
        UnmarshallingContext context) { 
      Birthday birthday = new Birthday(); 
      if (reader.getAttribute("gender").charAt(0) == 'm') { 
        birthday.setGenderMale(); 
      } else { 
        birthday.setGenderFemale(); 
      } 
      reader.moveDown(); 
      Person person = (Person)context.convertAnother(birthday, Person.class); 
      birthday.setPerson(person); 
      reader.moveUp(); 
      reader.moveDown(); 
      Calendar date = (Calendar)context.convertAnother(birthday, Calendar.class); 
      birthday.setDate(date); 
      reader.moveUp(); 
      return birthday; 
    } 

(Il est dans la dernière exemple/bloc de code sur la page)

HTH

EDIT:. Je voulais juste ajouter que vous aurez envie de passer par ce tutoriel entier, et non ju st chercher ce bloc de code. Vous devrez créer votre propre convertisseur et l'enregistrer avec votre instance XStream. (Probablement évident, mais juste au cas où ...)

3

Annoter votre classe comme si (vérifiez http://x-stream.github.io/annotations-tutorial.html pour plus de détails):

@XStreamAlias("cat") 
class Cat { 
    @XStreamAsAttribute 
    int age; 
    String name; 
} 

Maintenant, il suffit d'utiliser XStream comme suit:

xstream = new XStream(); 
xstream.processAnnotations(Cat.class); 
Cat roundtripGarfield = (Cat)xstream.fromXML(xstream.toXML(garfield)); 
+1

était juste écrire la même chose. Ajouter un lien vers les documents d'annotations: http://xstream.codehaus.org/annotations-tutorial.html – daveb

+0

@daveb: merci pour l'indice –

+0

+1 Cela m'a complètement échappé qu'il y aurait une annotation pour cela. Devrait avoir thunk ... – MCory