[英]Get attributes from nodelist using xpath in Java
XML XML
<Employees>
<Employee id="1" name="xyz">
<Employee id="2" name="abc">
</Employees>
I can get the list of Employee node with xpath expression我可以使用 xpath 表达式获取 Employee 节点列表
XPathExpression expr=xpath.compile("/Employees/Employee");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
How to get the attributes id, name from each node in the list.如何从列表中的每个节点获取属性 id、name。
尝试将您的 xpath 表达式更改为
/Employees/Employee/@id
You cannot ask a single list returning 2-tuples of (id, name) But you can have this in two separate node lists:您不能要求单个列表返回 (id, name) 的 2 元组但是您可以在两个单独的节点列表中使用它:
XPathExpression expr1 = xpath.compile("/Employees/Employee/@id");
NodeList nodes1 = (NodeList) expr1.evaluate(doc, XPathConstants.NODESET);
XPathExpression expr2 = xpath.compile("/Employees/Employee/@name");
NodeList nodes2 = (NodeList) expr2.evaluate(doc, XPathConstants.NODESET);
However, if having a single list is such important, some workaround are possible, for instance by concatenating both attributes values into a csv-like string:但是,如果拥有一个列表如此重要,则可以使用一些解决方法,例如将两个属性值连接到一个类似 csv 的字符串中:
XPathExpression expr = xpath.compile("concat(/Employees/Employee/@id, ';', /Employees/Employee/@name)");
which will return a list of 2 nodes:这将返回 2 个节点的列表:
"1;xyz"
"2;abc"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.