根据另一个孩子的文本获取节点的孩子

时间:2014-08-19 09:41:44

标签: java xpath

我想根据标题获取英文或匈牙利元素的文字。到目前为止,我想出了这个。你能用xpath帮我找一个更干净或更专业的解决方案吗?

XML:

<Textbook>
    <TEXT>
        <Title>SAMPLE TITLE 1</Title>
        <English>Sample english text</English>
        <Hungarian>Sample hungarian text</Hungarian>
    </TEXT>
    <TEXT>
        <Title>SAMPLE TITLE 2</Title>
        <English>Sample english text 2</English>
        <Hungarian>Sample hungarian text 2</Hungarian>
    </TEXT>
</Textbook>

代码:

public String getResults (String elementName, String language) throws XPathExpressionException {
    xpathFactory = XPathFactory.newInstance();
    xpath = xpathFactory.newXPath();
    XPathExpression expr = xpath.compile("/Textbook/TEXT/Title");
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        if (nodes.item(i).getTextContent().equals(elementName)) {
            XPathExpression expr2 = xpath.compile("/Textbook/TEXT/" + language);
            NodeList nodes2 = (NodeList) expr2.evaluate(doc, XPathConstants.NODESET);
            return nodes2.item(i).getTextContent();
        } 
    }
    return null;
}

1 个答案:

答案 0 :(得分:1)

您可以通过它的<TEXT>内容过滤<Title>。例如,此XPath将使<TEXT>具有内容等于“SAMPLE TITLE 1”的子<Title>

//TEXT[Title='SAMPLE TITLE 1']

因此,您可以使用单个XPath实际满足您的要求:

.....
String path = "/Textbook/TEXT[Title='" + elementName + "']/" + language
XPathExpression expr = xpath.compile(path);
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
    return nodes.item(i).getTextContent();
}
.....