2012-04-03 5 views
1

말 XPath는 자바에 다음과 같은 데이터베이스를 인덱스 값과 일치하는 방법 (일반적으로 그들은 훨씬 더 큰 것) :내가있어

<inventory> 
<book year="2000"> 
    <title>Snow Crash</title> 
    <author>Neal Stephenson</author> 
    <publisher>Spectra</publisher> 
    <isbn>0553380958</isbn> 
    <price>14.95</price> 
</book> 

<book year="2005"> 
    <title>Burning Tower</title> 
    <author></author> 
    <publisher>Pocket</publisher> 
    <isbn>0743416910</isbn> 
    <price>5.99</price> 
</book> 

<book year="1995"> 
    <title>Zodiac</title> 
    <author>Neal Stephenson</author> 
    <publisher>Spectra</publisher> 
    <isbn>0553573862</isbn> 
    <price>7.50</price> 
</book> 

<!-- more books... --> 

내가 책 제목과 저자를 모두 잡고 싶어 , 그리고 제목과 해당 작성자를 인쇄하십시오. 두 번째 항목은 작성자를 나열하지 않습니다. 나는 XPath가 3 권의 책 목록을 만들지 만 저자는 2 명 밖에 만들지 않는다는 것을 알았다. 따라서 각 목록의 동일한 인덱스 값을 사용하여 루프를 만들어 해당 Book/Author 콤보를 인쇄 할 수 없습니다. 첫 번째 항목에서만 작동하고 하나에서 벗어나서 결국에는 널 포인터 예외를 제공합니다. 저자 목록에 더 이상 입력 할 필요가 없습니다). 이 문제를 해결할 수있는 방법이 있습니까?

읽어 주셔서 감사합니다.

참고 : 지금까지 코드의 조각 :

그런 다음 각 book 요소에 titleauthor 요소, 예를 얻을, 모든 book 요소를 던져 반복해야
XPathExpression expr1 = xpath.compile("//pre:entry/pre:title/text()"); 
XPathExpression expr2 = xpath.compile("//pre:entry/pre:author/text()"); 

Object result1 = expr1.evaluate(doc, XPathConstants.NODESET); 
Object result2 = expr2.evaluate(doc, XPathConstants.NODESET); 

NodeList nodes1 = (NodeList) result1; 
NodeList nodes2 = (NodeList) result2; 

for (int i = 0; i < nodes1.getLength(); i++) { 
    System.out.println(nodes1.item(i).getNodeValue()); 
    System.out.println(nodes2.item(i).getNodeValue()); 
} 

답변

2

의사 코드 :

var bookNodes = XPath.select('//pre:book'); 
foreach book in booknodes 
    var title = book.select('pre:title'); 
    var author = book.select('pre:author'); 
+0

감사합니다. 이것은 정확하게 속임수입니다! – blaughli

+0

Java에서이 문제를 구현하는 데 문제가 있습니다. 어떤 조언을 주시면 감사하겠습니다. – blaughli

관련 문제