具有多个名称空间的JXPath

时间:2013-12-03 20:39:17

标签: java xml namespaces jaxb jxpath

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

Purchase.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());

Purchase.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

任何可以指出我正确方向来解决这个问题的想法都会被夸大?

1 个答案:

答案 0 :(得分:0)

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

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()