gpt4 book ai didi

java - Moxy 的 getValueByXPath 为除根元素以外的所有元素返回 null

转载 作者:行者123 更新时间:2023-11-30 11:13:10 25 4
gpt4 key购买 nike

See my sscce .

看例子,看起来我应该可以使用 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 而不是预期的对象吗?

最佳答案

由于您的 XML 文档是限定 namespace 的,因此您需要限定 namespace 来限定您的 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);
}

}

关于java - Moxy 的 getValueByXPath 为除根元素以外的所有元素返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26522398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com