2014-04-28 28 views
0

我有一個XML: -爲什麼xpath查詢對字母數字值失敗?

<?xml version="1.0" encoding="UTF-8" ?> 
    <sample> 
     <book year="2005"> 
      <title>Tower</title> 
      <author>Niven</author> 
      <author>Pournelle</author> 
      <publisher>Pocket</publisher> 
      <isbn>0743416910</isbn> 
      <price>5.99</price> 
     </book> 
     <book year="2005ad"> 
      <title>Burning</title> 
      <author>Larry</author> 
      <publisher>ABC</publisher> 
      <isbn>096543</isbn> 
      <price>0.99</price> 
     </book> 
     </sample> 

我使用XPath來得到使用一年的所有字段。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    factory.setNamespaceAware(true); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    Document doc = builder.parse("sample.xml"); 

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

    XPathExpression expr = xpath.compile("//book[@year=2005]/*"); 


    // xpath.compile("//book[@year=2005ad]/*"); 
    Object result = expr.evaluate(doc, XPathConstants.NODESET); 
    NodeList nodes = (NodeList) result; 

    for (int i = 0; i < nodes.getLength(); i++) { 

     Element el = (Element) nodes.item(i); 
     System.out.println("tag: " + el.getNodeName()); 

     if (el.getFirstChild().getNodeType() == Node.TEXT_NODE) 
      System.out.println("inner value:" + el.getFirstChild().getNodeValue()); 
    } 

當我使用 XPathExpression EXPR = xpath.compile( 「//書[@年= 2005]/*」); 我得到正確的輸出數據。

但是,當我使用 xpath.compile(「// book [@ year = 2005ad]/*」); 我沒有得到任何輸出數據。

每當使用「年」的任何字母數字數據時,我都沒有收到任何數據。 我很困惑爲什麼會出現這個問題。

回答

0

解決辦法是做這樣的(帶引號):

//book[@year="2005ad"]