2010-11-15 102 views
3

我想從一個XML文件中的屬性值,失敗,但我的代碼失敗,下面的異常:XPath表達式用於獲取屬性值在Java中

11-15 16:34:42.270: DEBUG/XpathUtil(403):異常= javax.xml.xpath.XPathExpressionException:javax.xml.transform.TransformerException中:額外非法令牌: '@', '源'

下面是我用得到的代碼節點列表:

private static final String XPATH_SOURCE = "array/[email protected]"; 
mDocument = XpathUtils.createXpathDocument(xml); 

NodeList fullNameNodeList = XpathUtils.getNodeList(mDocument, 
       XPATH_FULLNAME); 

這裏是我的XpathUtils類:

public class XpathUtils { 

    private static XPath xpath = XPathFactory.newInstance().newXPath(); 
    private static String TAG = "XpathUtil"; 

    public static Document createXpathDocument(String xml) { 
     try { 

      Log.d(TAG , "about to create document builder factory"); 
      DocumentBuilderFactory docFactory = DocumentBuilderFactory 
        .newInstance(); 
      Log.d(TAG , "about to create document builder "); 
      DocumentBuilder builder = docFactory.newDocumentBuilder(); 

      Log.d(TAG , "about to create document with parsing the xml string which is: "); 

      Log.d(TAG ,xml); 
      Document document = builder.parse(new InputSource(
        new StringReader(xml))); 

      Log.d(TAG , "If i see this message then everythings fine "); 

      return document; 
     } catch (Exception e) { 
      e.printStackTrace(); 
      Log.d(TAG , "EXCEPTION OCCURED HERE " + e.toString()); 
      return null; 
     } 
    } 

    public static NodeList getNodeList(Document doc, String expr) { 
     try { 
      Log.d(TAG , "inside getNodeList"); 
      XPathExpression pathExpr = xpath.compile(expr); 
      return (NodeList) pathExpr.evaluate(doc, XPathConstants.NODESET); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      Log.d(TAG, "exception = " + e.toString()); 
     } 
     return null; 
    } 

    // extracts the String value for the given expression 
    public static String getNodeValue(Node n, String expr) { 
     try { 
      Log.d(TAG , "inside getNodeValue"); 
      XPathExpression pathExpr = xpath.compile(expr); 
      return (String) pathExpr.evaluate(n, XPathConstants.STRING); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

我得到的getNodeList方法拋出的異常。

現在,根據http://www.w3schools.com/xpath/xpath_syntax.asp,要獲取屬性值,請使用「@」符號。但由於某種原因,Java正在抱怨這個標誌。

回答

6

嘗試

array/extConsumer/@source 

爲您的XPath表達式。這將選擇extConsumer元素的源屬性。

1

放一個斜槓屬性規範之前:

array/extConsumer/@source 
1

您鏈接W3Schools的頁面也說「謂語被嵌入在中括號」。您只需附加@source。嘗試

private static final String XPATH_SOURCE = "array/extConsumer[@source]"; 

編輯:
要清楚,這是如果你正在尋找一個單一的項目,這是你原來的措辭使我相信。如果你想收集一些源屬性,請參閱vanje和Anon的答案,建議使用斜線而不是方括號。