Search code examples
javaxmljaxbjaxb2

Is there a way to map the value of a node when the node also has inner nodes?


I'm currently using JAXB annotations, which work great for most cases. However, I've come across something I can't figure out how to process/create annotations for. I have the following XML:

   <animals>
      <animal>
        cat
        <age>5</age>
        <color>red</color>
      </animal>
   </animals>

Is there a way I can just get "cat" out of that XML without fetching "5" or "red"?

Here is what I have so far:

@XmlRootElement(name = "animals")
public class Animal {

    @XmlElement(name = "animal")
    String type;
}

But when I unmarshall this I just get an empty string.

Any help would be appreciated!

EDIT
Here is a full working example of what I'm trying to do:

@XmlRootElement(name = "animals")
private static class Animals {

    @XmlElement(name = "animals")
    String animalType;
}


    // This code is in "main"
    final String animalsXml = "<animals><animal>cat<color>red</color><age>5</age></animal></animals>";

    JAXBContext context = JAXBContext.newInstance(Animals.class);
    Unmarshaller um = context.createUnmarshaller();
    ByteArrayInputStream bais = new ByteArrayInputStream(animalsXml.getBytes("UTF-8"));

    Animals animals = (Animals)um.unmarshal(bais);

    boolean animalIsCat = animals.animalType == null ? false : animals.animalType.equalsIgnoreCase("cat");
    assert animalIsCat;
    // end code in main

Solution

  • Try something like this:

    @XmlRootElement(name = "animals")
    public class Animals {
    
        @XmlElement(name = "animal")
        List<Animal> animals;
    }
    
    public class Animal {
    
        @XmlMixed
        List<Object> content;
    }
    

    Now, the content field of Animal will contain a mix of String and JAXBElement objects. You'll need to examine them at runtime to extract the bits you want.