Вы можете использовать расширение EclipseLink JAXB (MOXy) @XmlPath, чтобы легко сделать это:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {
@XmlAttribute
private int uid;
@XmlAttribute
private String type;
private String name;
private String description;
private String myElement;
@XmlPath("myElement/@myAttr")
private String myAttr;
}
Этот класс будет взаимодействовать со следующим XML:
<myObject uid="42" type="someEnum">
<name>Waldo</name>
<description>yada yada</description>
<myElement myAttr="foo">some_string</myElement>
</myObject>
Используя следующий демонстрационный код:
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(MyObject.class);
File file = new File("input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
MyObject myObject = (MyObject) unmarshaller.unmarshal(file);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(myObject, System.out);
}
}
Чтобы указать MOXy в качестве реализации JAXB, вам нужно включить файл с именем jaxb.properties в тот же пакет, что и классы модели, со следующей записью:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Для получения дополнительной информации о сопоставлении на основе XPath MOXy см .: