I am using a combination of StAX and MOXy to parse XML files. When my parser detects that I am at a specified element, using XPaths, I unmarshal the element. Sometimes the XPath can represent multiple XML elements. Here is an example:
/a/b/*[self::c or self::d or self::e]
In this example these paths are all valid:
/a/b/c
/a/b/d
/a/b/e
In one of my POJOs I want to store the XML element name in a String variable, but I have not had any luck so far. The MOXy annotation @XmlVariableNode is very close to what I want, however I don't have a parent object and I don't want one. I have also tried using the MOXy annotation @XmlPath, but it seems that MOXy doesn't support the XPath functions name() or local-name(). Here is a simple example of my last attempt:
POJO
public class Data extends DataObject {
private String source;
public String getSource() {
return source;
}
@XmlPath("./name()")
public void setSource(String source) {
this.source = source;
}
}
unmarshaller:
protected DataObject unmarshallElement(Class<? extends DataObject> marshallingClass) throws JAXBException {
DataObject retVal = null;
if(marshallingClass != null) {
Unmarshaller jaxbUnmarshaller = jaxbUnmarshallerMapping.get(marshallingClass);
if(jaxbUnmarshaller != null) {
JAXBElement<? extends DataObject> dataObject = jaxbUnmarshaller.unmarshal(xmlStreamReader, marshallingClass);
retVal = dataObject.getValue();
}
else
throw new IllegalArgumentException("No unmarshaller could be found for " + marshallingClass.getName());
}
else
throw new IllegalArgumentException("No object class was provided");
return retVal;
}
I am sure I could do something ugly in my unmarshaller like below, but I really don't want to.
JAXBElement<? extends DataObject> dataObject = jaxbUnmarshaller.unmarshal(xmlStreamReader, marshallingClass);
retVal = dataObject.getValue();
if(dataObject instanceof SomeClass)
retVal.setSource(dataObject.getName().getLocalPart());
Is it possible to store the current elements name in a variable using MOXy or JAXB in general?