2013-05-31 38 views
-2

過去兩天我一直堅持這個任務,並沒有通過不同的文章得到任何明確的解決方案。所以請給我一步一步的代碼來檢索XML中存在的XPath值。如何閱讀java中的XML xpath

我的XML是

<bookstore> 
    <book> 
    <int name="sno">1</int> 
    <str name="author">J K. Rowling</str> 
    <int name="price">29.99</int> 
    <str name="subauthor">J K</str> 
    </book> 
    <book> 
    <int name="sno">2</int> 
    <str name="author">J K. Rowling</str> 
    <int name="price">29.99</int> 
    <str name="subauthor">hamilton</str> 
    </book> 
</bookstore> 

在這個XML我需要每個作者,價格和subauthor值。 我預期的結果是:

(author-J K. Rowling,price-29.99,subauthor-j k) 

再怎麼從這個XML得到subauthor的最後一個值。

我的java代碼來得到這個值是行不通的。它只拋出一個例外。

public gettheXMLvalues() { 
    try { 
    NodeList nodeLst1 = doc.getElementsByTagName("doc"); 
    for (int i = 0; i < nodeLst1.getLength(); i++) { 
     Node node = nodeLst1.item(i); 
     if (node.getNodeType() == Node.ELEMENT_NODE) { 
     Element element = (Element) node; 
     NodeList nodes = element.getElementsByTagName("//str[@name='author']").item(0).getChildNodes(); 
     node = (Node) nodes.item(0); 
     System.out.println("ELEMETS " + element.getTextContent()); 
     System.out.println("Author" + node.getNodeValue()); 
     } 
    } catch(Exception e){ 
    system.out.println("Exception "+e); 
    } 
} 

請給我一個解決方案,使作者,價格和每個book.I的subauthor價值試過很多事情得到結果,但不幸的是我沒有得到的結果。請給我清楚的解決方案。

+0

什麼異常? – fGo

+0

發佈異常跟蹤 –

+4

我不認爲'getElementsByTagName'方法接受Xpath表達式。你可以更好地做這樣的事情: 'XPathExpression expr = xpath.compile(「/ bookstore/book/int [@ name ='price']/url」); NodeList nl =(NodeList)expr.evaluate(doc,XPathConstants.NODESET);'。看看這個http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java – fGo

回答

0

公共靜態的ArrayList gettheXMLvalues(文檔XMLDOCUMENT,串作者)拋出異常{

ArrayList<String> result = new ArrayList<String>(); 

    List<Element> elementList = xmlDocument.selectNodes("//str[@name='author']"); 

    if (elementList == null) { 
     return result; 
    } 

    ArrayList<Element> listAuthor = new ArrayList<Element>(); 

    for (int i = 0; i < elementList.size(); i++) { 
     Element el = elementList.get(i); 
     if (el.getText().equalsIgnoreCase(author)) { 
      listAuthor.add(el); 
     } 
    } 

    if (listAuthor.size() == 0) { 
     return result; 
    } 
    else { 
     String authorLine = ""; 

     for (int i = 0; i < listAuthor.size(); i++) { 

      Element element = listAuthor.get(i); 

      Element price = (Element)element.getParent().selectSingleNode("./int[@name='price']"); 
      Element subauthor = (Element) element.getParent().selectSingleNode("./str[@name='subauthor']"); 

      authorLine = "author-" + author + ",price-" + price.getText() + ",subauthor-" + subauthor.getText(); 

      result.add(authorLine); 
     } 
    } 

    return result; 
}