【发布时间】:2021-08-13 17:56:38
【问题描述】:
我在 Java 中使用 xPath,我想检索节点 team1_win_perc、team2_win_perc 和 draw_perc。这是xml文档:
<stats timestamp="1628874073" date="08/13/2021 12:01:13">
<common>
<EV_AVERAGE_HOME>0.006669</EV_AVERAGE_HOME>
<EV_AVERAGE_AWAY>0.00193</EV_AVERAGE_AWAY>
<EV_AVERAGE_DRAW>0.007402678</EV_AVERAGE_DRAW>
</common>
<games>
<id348812>
<gameid gsid="3509729">348812</gameid>
<league>BUND</league>
<team1RotationNumber>150540</team1RotationNumber>
<team1Name>Bayern Munchen</team1Name>
<team1_win_perc>62.1</team1_win_perc>
<team2RotationNumber>150541</team2RotationNumber>
<team2Name>Arsenal</team2Name>
<team2_win_perc>17.8</team2_win_perc>
<draw_perc>20.1</draw_perc>
</id348812>
<id348813>
<gameid gsid="3509730">348813</gameid>
<league>EPL</league>
<team1RotationNumber>150543</team1RotationNumber>
<team1Name>Tottenham</team1Name>
<team1_win_perc>50</team1_win_perc>
<team2RotationNumber>150544</team2RotationNumber>
<team2Name>Chelsea</team2Name>
<team2_win_perc>25</team2_win_perc>
<draw_perc>25</draw_perc>
</id348813>
</games>
</stats>
这是我到目前为止所做的事情:
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document document = db.parse(new InputSource(
new ByteArrayInputStream(xmlResponseString.getBytes(UTF_8))));
final XPathFactory xpathFactory = XPathFactory.newInstance();
final XPath xpath = xpathFactory.newXPath();
NodeList gameIds = (NodeList) xpath.evaluate("stats/games/*",
document, NODESET);
final List<Double> homeWinPercentages = new ArrayList<>();
final List<Double> awayWinPercentages = new ArrayList<>();
final List<Double> drawPercentages = new ArrayList<>();
for (int i = 0; i < gameIds.getLength(); ++i) {
Node node = gameIds.item(i);
homeWinPercentages.add(Double.valueOf((String) xpath.evaluate("stats/games/"
+ node.getNodeName() + "/team1_win_perc", document, STRING)));
awayWinPercentages.add(Double.valueOf((String) xpath.evaluate("stats/games/"
+ node.getNodeName() + "/team2_win_perc", document, STRING)));
drawPercentages.add(Double.valueOf((String) xpath.evaluate("stats/games/"
+ node.getNodeName() + "/draw_perc", document, STRING)));
}
有没有办法避免对 xml 文档进行 3 次评估?我想创建一个List 类Probability,其中包括team1_win_perc、team2_win_perc 和draw_perc 字段。
【问题讨论】:
-
XPath 和“循环”? Java端你到底想要哪些数据,你能显示结果吗?您是否知道使用开源 Saxon 10 HE 库轻松支持 Java 的 XPath 版本为 3.1。当然,您需要使用自己的 API 来利用 XPath 3.1 的强大功能,JAXP XPath API 面向 XPath 1.0,但是使用 XPath 3.1,您可以轻松选择并返回三个数组的序列或三个序列的数组,甚至具有三个不同属性的地图,代表您的三个列表。
-
@MartinHonnen 我设法更进一步,编辑了问题。我想知道是否可以在一次调用中做我想做的事情,而不是对我想要的每个字段进行三个单独的评估。