2013-07-12 81 views
0

我有這樣而使用XPath

<Processed> 
    <address> 
     <buildingnumber> 29 </buildingnumber> 
     <street> South Lasalle Street</street> 
     <city>Chicago</city> 
     <state>Illinois</state> 
     <zip>60603</zip> 
    </address> 

    <address> 
     <buildingnumber> 30 </buildingnumber> 
     <street> West Street</street> 
     <city>xxx</city> 
     <state>yyy</state> 
     <zip>12345</zip> 
    </address> 
</Processed> 

一個XML我使用下面的代碼,以打印值解析XML記錄之間如何differentitae

DocumentBuilder builder = tryDom.getDocumentBuilder(); 
xmlDocument = tryDom.getXmlDocument(builder, file); 

factory = XPathFactory.newInstance(); 
xPath = factory.newXPath(); 

String expression8 = "//address/descendant-or-self::*[not(*)]"; 

try { 

    xPathExpression = xPath.compile(expression8); 
    Object result = xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET); 
    printXpathResult(result); 

} catch (XPathExpressionException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
} 

public static void printXpathResult(Object result){ 

    NodeList nodes = (NodeList) result; 

    for (int i = 0; i < nodes.getLength(); i++) { 
     Node node = nodes.item(i); 
     String nodeName = node.getNodeName(); 
     String nodeValue = node.getTextContent(); 

     System.out.println(nodeName + " = " + nodeValue); 
    } 
} //end of printXpathResult() 

它給我像

輸出
buildingnumber = 29 
street = South Lasalle Street 
city = Chicago 
state = Illinois 
zip = 60603 
buildingnumber = 30 
street = West Street 
city = xxx 
state = yyy 
zip = 12345 

但問題是我不知道何時一個地址是結束和其他開始。我想要在zip = 60603之後。我知道第一個地址是結束,其他地址正在啓動。我怎樣才能區分記錄?

感謝

+0

你知道地址節點的數量出現在相關的 –

+0

之前嗎?不是,因爲實時我從網上得到xml,我不知道有多少地址記錄會出現......我希望那每個記錄一些我如何知道新記錄開始... – Basit

+3

我會建議將您的xpaht更改爲「//地址」,並且比迭代結果NodeList的子項(現在是「地址」。 –

回答

0

這會給你擁有你知道拉鍊地址節點的位置(可以說是X)

count(Processed/address[zip='60603']/preceding-sibling::*)+1 

然後使用

String expression8 = "//address[x+1]/descendant-or-self::*[not(*)]"; 

試試吧。