[英]Get specific value of node by attribute value
<row id="1">
<column name="Date">30.01.2029 00:00:00 +02:00</column>
<column name="Jackpot ID">sol_3430_32488</column>
<column name="Jackpot Name">Level1</column>
<column name="Jackpot Value">0</column>
<column name="Casino Seed">87.5</column>
<column name="Currency">USD</column>
</row>
我写了这段代码得到它,我认为用索引调用不是个好主意,有时 xml 不包含货币并且失败
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setNamespaceAware(false);
f.setValidating(false);
DocumentBuilder b = f.newDocumentBuilder();
URLConnection urlConnection = new URL(url).openConnection();
urlConnection.addRequestProperty("Accept", "application/xml");
Document doc = b.parse(urlConnection.getInputStream());
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("row");
for (int itr = 0; itr < nodeList.getLength(); itr++) {
Node node = nodeList.item(itr);
ArrayList<String> tabInfo = new ArrayList<>();
if (node.getNodeType() ==Node.ELEMENT_NODE) {
Element eElement = (Element) node;
String data = eElement.getElementsByTagName("column").item(0).getTextContent();
String jpId = eElement.getElementsByTagName("column").item(1).getTextContent();
String jpValue = eElement.getElementsByTagName("column").item(2).getTextContent();
String casinoName = eElement.getElementsByTagName("column").item(3).getTextContent();
String casinoSeed = eElement.getElementsByTagName("column").item(4).getTextContent();
String casinoCurrency = eElement.getElementsByTagName("column").item(5).getTextContent();
有没有办法通过属性进行交互? 如果有数据,累积奖金等。 把它返还
您可以按如下方式使用 xpath 通过属性值读取元素:
XPath xPath = XPathFactory.newInstance().newXPath();
String expressionJackpotID = "//column[@name='Jackpot ID']/text()";
String expressionJackpotName = "//column[@name='Jackpot Name']/text()";
// etc
String expressionCurrency = "//column[@name='Currency']/text()";
XPathExpression compiledExpressionJackpotID = xPath.compile(expressionJackpotID);
XPathExpression compiledExpressionJackpotName = xPath.compile(expressionJackpotName);
//etc
XPathExpression compiledExpressionCurrency = xPath.compile(expressionCurrency);
NodeList nodeList = doc.getElementsByTagName("row");
for (int itr = 0; itr < nodeList.getLength(); itr++) {
Node node = nodeList.item(itr);
List<String> tabInfo = new ArrayList<>();
if (node.getNodeType() == Node.ELEMENT_NODE) {
String jackpotId = (String) compiledExpressionJackpotID.evaluate(node, XPathConstants.STRING);
String jackpotName = (String) compiledExpressionJackpotName.evaluate(node, XPathConstants.STRING);
// etc
String currency = (String) compiledExpressionCurrency.evaluate(node, XPathConstants.STRING);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.