查看示例,看起来我应该能够使用moxy' getValueByXPath来访问umarshalled xml对象的子元素。但相反,我总是返回null。可以访问根对象上的属性。
当我在this question's answer中运行示例时,它运行正常:/这是我正在做的事情:
的xml:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_HotelInvCountNotifRQ xmlns="http://www.opentravel.org/OTA/2003/05" AltLangID="alt lang id fnord">
<Inventories AreaID="areaID_fnord">
<Inventory>
<UniqueID ID="inventory unique id fnord"/>
</Inventory>
</Inventories>
</OTA_HotelInvCountNotifRQ>
的java:
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
....
OTAHotelInvCountNotifRQ rq = ...
JAXBContext ctx = (JAXBContext) JAXBContextFactory.createContext("org.opentravel.ota._2003._05", Main.class.getClassLoader());
String altLangId = ctx.getValueByXPath(rq, "@AltLangID", null, String.class);
assertThat("rq's altlang attr", altLangId, is(ALT_LANG_ID));
InvCountType inventories = ctx.getValueByXPath(rq, "Inventories", null, InvCountType.class);
assertThat("inventories", inventories, is(not(nullValue())));
我有一个可运行的simple self-contained complete example(mvn exec:java
)。我无法更改OTA类(我是从xsd生成它们并为方便起见而包含它们)。
为什么这会返回null而不是预期的对象?
答案 0 :(得分:1)
由于您的XML文档是名称空间限定的,因此您需要命名空间限定您的XPath。然后,您需要使用NamespaceResolver
的实例为命名空间映射配对提供前缀。这将作为参数传递给getValueByXPath
方法。
import java.io.File;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBHelper;
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.opentravel.ota._2003._05.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance("org.opentravel.ota._2003._05", ObjectFactory.class.getClassLoader(), null);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input.xml");
OTAHotelInvCountNotifRQ rq = (OTAHotelInvCountNotifRQ) unmarshaller.unmarshal(xml);
NamespaceResolver nsResolver = new NamespaceResolver();
nsResolver.put("ns", "http://www.opentravel.org/OTA/2003/05");
InvCountType inventories = JAXBHelper.getJAXBContext(jc).getValueByXPath(rq, "ns:Inventories", nsResolver, InvCountType.class);
System.out.println(inventories);
}
}