First, I must say that I find Xpath
as a very nice parser , and I guess pretty powerful when comparing it to other parsers .
Given the following code :
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("input.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
If I wanted to find the first
node of Round 1 & Door 1 , here :
<Game>
<Round>
<roundNumber>1</roundNumber>
<Door>
<doorName>abd11</doorName>
<Value>
<xVal1>0</xVal1>
<xVal2>25</xVal2>
<pVal>0.31</pVal>
</Value>
<Value>
<xVal1>25</xVal1>
<xVal2>50</xVal2>
<pVal>0.04</pVal>
</Value>
<Value>
<xVal1>50</xVal1>
<xVal2>75</xVal2>
<pVal>0.19</pVal>
</Value>
<Value>
<xVal1>75</xVal1>
<xVal2>100</xVal2>
<pVal>0.46</pVal>
</Value>
</Door>
<Door>
<doorName>vvv1133</doorName>
<Value>
<xVal1>60</xVal1>
<xVal2>62</xVal2>
<pVal>1.0</pVal>
</Value>
</Door>
</Round>
<Round>
<roundNumber>2</roundNumber>
<Door>
<doorName>eee</doorName>
<Value>
<xVal1>0</xVal1>
<xVal2>-25</xVal2>
<pVal>0.31</pVal>
</Value>
<Value>
<xVal1>-25</xVal1>
<xVal2>-50</xVal2>
<pVal>0.04</pVal>
</Value>
<Value>
<xVal1>-50</xVal1>
<xVal2>-75</xVal2>
<pVal>0.19</pVal>
</Value>
<Value>
<xVal1>-75</xVal1>
<xVal2>-100</xVal2>
<pVal>0.46</pVal>
</Value>
</Door>
<Door>
<doorName>cc</doorName>
<Value>
<xVal1>-60</xVal1>
<xVal2>-62</xVal2>
<pVal>0.3</pVal>
</Value>
<Value>
<xVal1>-70</xVal1>
<xVal2>-78</xVal2>
<pVal>0.7</pVal>
</Value>
</Door>
</Round>
</Game>
I'll do this :
XPathExpression expr = xpath.compile("//Round[1]/Door[1]/Value[1]/*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
and if I wanted the second
node of Round 1 & Door 1 then :
XPathExpression expr = xpath.compile("//Round[1]/Door[1]/Value[2]/*/text()");
but how do I do this using a loop , since I don't know how much Value-nodes
I have , meaning how can I do this using a loop , where each iteration I retrieve 3 (I mean the xVal1
, xVal2
and pVal
values ) more values of a Value node !?
The reasons for asking for this are :
I don't know how much
Round
-s I haveI don't know how much
Value
-s I haveI don't want to declare every time a new
XPathExpression
Thanks .