XPath:提取多个子节点值

时间:2018-04-17 20:39:55

标签: java xpath nodes

我正在尝试使用XPath从<to>多个节点中提取值,但我得到的只是第一个值

SOAP看起来像:

<addressBlock xmlns:i="http://www.w3.org/2001/XMLSchema-instance" s:relay="1">
    <from>mailto:user1@test.local</from>
    <to>mailto:user2@test.local</to>
    <to>mailto:user3@test2.local</to>
</addressBlock>

我的代码如下:

private String extractFieldFromXml(Document doc, XPath xPath, String expression)
{
    try
    {
        Node node = (Node) xPath.compile(expression).evaluate(doc, XPathConstants.NODE);
        return node == null ? null : node.getTextContent();
    } catch (XPathExpressionException e)
    {
        log.info(e.getMessage());
        return null;
    }

}

然后我试着这样做:

String to = extractFieldFromXml(doc, xpath, msgExpression);

for (Iterator<String> to = to.iterator(); to.hasNext();) {
   String value = to.next();
   System.out.println(value);
}

2 个答案:

答案 0 :(得分:1)

获取所有z值的XPath是

to

此表达式返回/addressBlock/to 个字符串的串联 使用Java在此结果的所有项目上运行to/text()

答案 1 :(得分:0)

如果有人要寻找解决方案,那么工作代码如下:

private String extractFieldFromXml(Document doc, XPath xPath, String expression)
{
    if (expression.equals(RECIPIENT_EXPRESSION)) {
        try
        {
            NodeList nodes = (NodeList) xPath.evaluate(expression,doc, XPathConstants.NODESET);

            ArrayList<String> recipientsList = new ArrayList<String>();

            for (int i = 0; i < nodes.getLength(); i++){

                Node node = nodes.item(i);
                if (node != null) {
                    String recipient = node.getTextContent();
                    recipientsList.add(recipient);
                }
            }

            String recipients = StringUtils.join(recipientsList,",");
            return recipients == null ? null: recipients;

        } catch (XPathExpressionException e)
        {
            log.info(e.getMessage());
            return null;
        }
    }
    else {
        try
        {
            Node node = (Node) xPath.compile(expression).evaluate(doc, XPathConstants.NODE);
            return node == null ? null : node.getTextContent();
        } catch (XPathExpressionException e)
        {
            log.info(e.getMessage());
            return null;
        }
    }
}