2016-09-29 67 views
0

我無法使xpath表達式正常工作。我正在使用駱駝2.15.1。任何幫助將不勝感激。駱駝使用xpath檢索xml標籤名稱

我已經試過以下

<xpath>name(//*[1])='PPR_PC2'</xpath> 
<xpath>name("//*[local-name()='PPR_PC2')</xpath> 
<xpath>//PPR_PC2</xpath> 

我的XML文件

<?xml version="1.0" encoding="UTF-8"?> 
<PPR_PC2 xmlns="urn:hl7-org:v2xml"> 
    <MSH> 
     <MSH.1>|</MSH.1> 
     ... 
     ... 
    </MSH> 
    ... 
    ... 
</PPR_PC2> 

我的駱駝航線

<route id="_route_1"> 
    <from uri="activemq:queue:myQIN"/> 

    <doTry> 
     <choice> 
      <when> 
       // This path works without having namespace 
       <xpath>name(//*[1])='PPR_PC2'</xpath> 
       <to uri="xslt:transform/stylesheet.xsl"/> 
       <to uri="..."/> 
      </when> 
      <otherwise> ... </otherwise> 
     </choice> 
     <doCatch> ... </doCatch> 
    </doTry> 
</route> 

這是我得到

[thread #1 - JmsConsumer[myQIN]] EndpointMessageListener 
    WARN Execution of JMS message listener failed. 
    Caused by: [org.apache.camel.builder.xml.InvalidXPathExpression - Invalid xpath: name(//*[1])='PPR_PC2'. 
    Reason: javax.xml.xpath.XPathExpressionException: net.sf.saxon.trans.XPathException: 
    A sequence of more than one item is not allowed as the first argument of name() (<PPR_PC2/>, <MSH/>, ...) ] 
org.apache.camel.builder.xml.InvalidXPathExpression: 
    Invalid xpath: name(//*[1])='PPR_PC2'. 
    Reason: javax.xml.xpath.XPathExpressionException: net.sf.saxon.trans.XPathException: 
    A sequence of more than one item is not allowed as the first argument of name() (<PPR_PC2/>, <MSH/>, ...) 
錯誤3210

回答

1

該錯誤消息

多個項目的序列是不允許的名稱()

的第一個參數暗示當你寫下你的時候

name(//*[1]) 

(其中選擇每一個元素是其父母的第一個孩子)

你可能是指

name((//*)[1]) 

(其中選擇文檔中的第一個元素)

儘管這會給你完全一樣

name(/*) 
+0

謝謝邁克爾,那工作很好。 – user1998820

0

聲明命名空間並使用它。請注意下面的xmlns

<route id="_route_1" xmlns:hl7="urn:hl7-org:v2xml"> 
    <from uri="activemq:queue:myQIN"/> 

    <doTry> 
     <choice> 
      <when> 
       <xpath>/hl7:PPR_PC2</xpath> 
       <to uri="xslt:transform/stylesheet.xsl"/> 
       <to uri="..."/> 
      </when> 
      <otherwise> ... </otherwise> 
     </choice> 
     <doCatch> ... </doCatch> 
    </doTry> 
</route> 

您可以選擇任何您喜歡的前綴,但必須選擇一個前綴才能聲明和使用名稱空間。例如,我選擇了hl7

在您的XML文件中聲明更高的名稱空間,以便能夠在多個位置使用它。

使用另外讀how to use xpath in camel-context.xml to check if a particular node is exist or not

0

嘗試:

Namespaces ns = new Namespaces("cus","http://..."); 

ns.xpath("//MSH.1/text()", java.lang.String.class)