我有像这样的xml
<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>
我使用以下代码来打印值
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)
这将为您提供已知拉链的地址节点的位置(让我们说它是x)
count(Processed/address[zip='60603']/preceding-sibling::*)+1
然后使用
String expression8 = "//address[x+1]/descendant-or-self::*[not(*)]";
试试吧。