How to assign a boolean based on the existence of an element in JAXB?

This is somewhat related to this question and this question that I asked yesterday.

I would like to use a boolean to determine if an element exists in an XML document. The files I process allow for elements such as:

<FamilyMember>
    <Name>Jeff</Name>
</FamilyMember>
<FamilyMember>
    <Name>Spot</Name>
    <IsPet/>
</FamilyMember>

In this example, the element indicates that FamilyMember is a pet, but there is no additional data associated with this element. I would like to be able to tell JAXB to return a boolean based on whether an element exists in the parsed file. If an element exists, the value must be true; otherwise it must be false. I would like to do this from the XSD schema that I use to generate my Java classes, if possible.

+3
source share
2 answers

You should be able to do this with an XmlAdapter similar to the following:

( (), JAXB / ?), .


, . , EclipseLink JAXB (MOXy), , JAXB.

FamilyMember

package example;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name="FamilyMember")
public class FamilyMember {

    private boolean pet;
    private String name;

    @XmlElementRef
    @XmlJavaTypeAdapter(IsPetAdapter.class)
    public boolean isPet() {
        return pet;
    }

    public void setPet(boolean pet) {
        this.pet = pet;
    }

    @XmlElement(name="Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

IsPetAdapter

package example;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import forum204.IsPetAdapter.IsPet;

public class IsPetAdapter extends XmlAdapter<IsPet, Boolean> {

    @Override
    public Boolean unmarshal(IsPet v) throws Exception {
        return null != v;
    }

    @Override
    public IsPet marshal(Boolean v) throws Exception {
        if(v) {
            return new IsPet();
        }
        return null;
    }

    @XmlRootElement(name="IsPet")
    public static class IsPet {
    }

}

Demo

package example;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

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

        Unmarshaller unmarshaller= jc.createUnmarshaller();
        FamilyMember fm = (FamilyMember) unmarshaller.unmarshal(new File("input.xml"));

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

}
+3

IsPet ? , , XML. , , .

0

All Articles