2013-05-15 51 views
0

大家好對問題進行的xpath的xpath不接受這個表達式

/ABCD/nsanity/component_details [@成分= 「UCS」]/command_details [< * configScope inHierarchical = 「真」 的Cookie =」 {COOKIE}」 DN =‘ORG-根’* />]/collected_data

我要檢索的字符串的XPath語句以上,但是當我給這個XPath來XPath來evaulate它被拋出表達異常像

引起的:javax.xml.transform.TransformerException:預期位置路徑,但遇到以下標記:< configScope

+1

請向我們展示一個數據示例並正確格式化代碼(是否包含在查詢中的星星?)。閱讀關於如何格式化您的文章的[常見問題]。 –

+0

沒有星不包含在我的查詢< and />符號拋出異常 – Gopal

+0

如果下面的答案不符合您的期望,請重新考慮我在我之前的評論中發佈的內容。因爲這個問題很模糊。你的意思是「沒有不包含在我的查詢中的明星」? –

回答

1

XPath表達式中的粗體部分不是有效的謂詞表達式。我只能猜測,你想達到什麼目的。如果你只想要<command_details/>元素,這與設置爲inHierarchical="true"cookie="{COOKIE}"dn="org-root"屬性的<configScope/>子元素,則XPath表達式應該是:

/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data 

下面是一個例子XML:

<abcd> 
    <nsanity> 
    <component_details component="ucs"> 
     <command_details> 
     <configScope inHierarchical="true" cookie="{COOKIE}" dn="org-root" /> 
     <collected_data>Yes</collected_data> 
     </command_details> 
     <command_details> 
     <configScope inHierarchical="true" cookie="{COOKIE}" dn="XXX"/> 
     <collected_data>No</collected_data> 
     </command_details> 
    </component_details> 
    </nsanity> 
</abcd> 

以下Java程序讀取XML文件test.xml並評估XPath表達式(並打印元素<collected_data/>的文本節點。

import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.xpath.XPath; 
import javax.xml.xpath.XPathConstants; 
import javax.xml.xpath.XPathFactory; 

import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.NodeList; 


public class Test { 

    public static void main(String[] args) throws Exception { 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    Document document = dbf.newDocumentBuilder().parse("test.xml"); 

    XPath xpath = XPathFactory.newInstance().newXPath() ; 

    NodeList nl = (NodeList) xpath.evaluate("/abcd/nsanity/component_details[@component='ucs']/command_details[configScope[@inHierarchical='true' and @cookie='{COOKIE}' and @dn='org-root']]/collected_data", document, XPathConstants.NODESET); 
    for(int i = 0; i < nl.getLength(); i++) { 
     Element el = (Element) nl.item(i); 
     System.out.println(el.getTextContent()); 
    } 
    } 
}