как сопоставить значения индекса в XPath Java

Скажем, у меня есть следующая база данных (обычно они будут намного больше):

<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... -->

I want to grab all of the book titles and authors, and then print out the titles and the corresponding authors. Notice that the second entry does not list an author. I've found that XPath will create a list of 3 books, but of only 2 authors. Therefore I can't print the corresponding Book/Author combos by making a loop using the same index values from each list (it will only work for the first entry, then gets off by one, and eventually gives a null pointer exception when there are no more entries in the author list). Is there a way to get around this issue?

Спасибо за чтение.

Примечание. Часть кода на данный момент:

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());
}

person blaughli    schedule 03.04.2012    source источник


Ответы (1)


Вы должны перебрать все элементы book, затем в каждом элементе book получить элементы title и author, например в псевдокоде:

var bookNodes = XPath.select('//pre:book');
foreach book in booknodes
    var title = book.select('pre:title');
    var author = book.select('pre:author');
person Kirill Polishchuk    schedule 03.04.2012
comment
У меня проблемы с реализацией этого в Java. Любой совет будет принят во внимание. - person blaughli; 04.04.2012