1

我需要使用 JXPath 在 JAXB 生成的对象上创建一个查询。下面的试用代码生成以下错误:线程“main”中的异常 org.apache.commons.jxpath.JXPathNotFoundException: No value for xpath: //p:OrderDetail

购买.xml

<?xml version="1.0"?>
<!-- Created with Liquid XML Studio 0.9.8.0 (http://www.liquid-technologies.com) -->
<p:Purchase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://NamespaceTest.com/Purchase Main.xsd" 
            xmlns:p="http://NamespaceTest.com/Purchase"
            xmlns:o="http://NamespaceTest.com/OrderTypes"
            xmlns:c="http://NamespaceTest.com/CustomerTypes"
            xmlns:cmn="http://NamespaceTest.com/CommonTypes">
<p:OrderDetail>
 <o:Item>
   <o:ProductName>Widget</o:ProductName>
   <o:Quantity>1</o:Quantity>
   <o:UnitPrice>3.42</o:UnitPrice>
  </o:Item>
 </p:OrderDetail>
 <p:PaymentMethod>VISA</p:PaymentMethod>
 <p:CustomerDetails>
  <c:Name>James</c:Name>
  <c:DeliveryAddress>
   <cmn:Line1>15 Some Road</cmn:Line1>
   <cmn:Line2>SomeTown</cmn:Line2>
  </c:DeliveryAddress>
  <c:BillingAddress>
   <cmn:Line1>15 Some Road</cmn:Line1>
   <cmn:Line2>SomeTown</cmn:Line2>
  </c:BillingAddress>
 </p:CustomerDetails>
</p:Purchase>

审判...

JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller um = ctx.createUnmarshaller();
Purchase purchase = (Purchase) um.unmarshal(new File("Purchase.xml"));  

JXPathContext jctx = JXPathContext.newContext(purchase);
jctx.registerNamespace("p", "http://NamespaceTest.com/OrderTypes");
OrderType cust = (OrderType) jctx.getValue("//p:OrderDetail");
System.out.println(cust.getItem());

购买.java

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

    @XmlElement(name = "OrderDetail", required = true)
    protected OrderType orderDetail;

    /**
 * Gets the value of the orderDetail property.
 * 
 * @return
 *     possible object is
 *     {@link OrderType }
 *     
 */
public OrderType getOrderDetail() {
    return orderDetail;
}

xml 文件取自:http ://www.liquid-technologies.com/Tutorials/XmlSchemas/XsdTutorial_04.aspx

任何可以为我指出解决此问题的正确方向的想法都会被接受?

4

1 回答 1

0

由于您正在构建一个未JXPathContext编组的对象树(而不是直接从 xmlDocument或构建它Element),因此您不必担心名称空间。

JXPathContext context = JXPathContext.newContext(purchase);
OrderType orderDetail = (OrderType) context.getValue("orderDetail");
// equivalent to purchase.getOrderDetail()

for(Iterator iter = context.iterate("/orderDetail/items"); iter.hasNext()){
   Item i = (Item) iter.next();
   //...
}
// Assumes that OrderType has a items property
// List<Item> getItems()
于 2013-12-04T01:31:57.587 回答