如何检查是否已到达父节点Java的最后一个子节点

时间:2016-04-26 22:47:21

标签: java xml xml-parsing

我有一个XML响应,我想解析。而且我似乎有它工作,但我想知道,如何(在Java代码中)我可以知道我已经到达父节点的lastChild

XML:

<Data>
    <Lambda>Test</Lambda>
    <Gr>Function</Gr>
    <Approach>Method</Approach>
    <Sentence>
        <Text id="1">You are tall because </Text>
        <Entry id="2">ApplicableConditions</Entry>
        <Text id="3">.</Text>
    </Sentence>
</Data>

代码:

String sentence = new String();
List<String> sentList = new ArrayList<>();
sentence += node.getTextContent();
// If last sibling and no children, then put current sentence into list
if(!node.hasChildNodes() && !node.getLastChild().hasChildNodes()) { 
    sentList.add(sentence);
}

例如,当当前节点处于Text id = 3时,如何查看这确实是父节点Sentence的最后一个子节点?这样我就可以将构造的句子添加到列表中并稍后阅读。

这样我将在发送列表中包含以下字符串项:

  

你很高,因为ApplicableConditions。

编辑:

<Data>
    <Lambda>Test</Lambda>
    <Gr>Function</Gr>
    <Approach>Method</Approach>
    <Sentence>
        <Text id="1">You are tall because </Text>
        <Entry id="2">ApplicableConditions</Entry>
        <Text id="3">.</Text>
    </Sentence>
</Data>

<Data>
    <Lambda>Test2</Lambda>
    <Gr>Fucntion</Gr>
    <Approach>Method</Approach>
    <Sentence>
        <Text id="1">Because you don't have any qualifying dependents and you are outside the eligible age range, </Text>
        <Entry id="2">you don't qualify for this credit.</Text>
        <BulletedList id="3">
            <QuestionEntry id="4">
                <Role>Condition</Role>
            </QuestionEntry>
        </BulletedList>
    </Sentence>
</Data>

注意第二个,结构略有不同......如何考虑不同的结构。我的解决方案似乎没有在这里工作......因为句子的最后一个孩子没有属性。也许更好地使用Xpaths?

1 个答案:

答案 0 :(得分:0)

这似乎解决了我的问题。我找到了最后一个兄弟,然后只是将当前的Node属性值与最后一个节点属性值进行比较,如果它们相同则将构造的句子添加到字符串List中。

<强>代码:

...
Element ele = (Element) node;
if(ele.getAttribute("id") == getLastChildElement(nNode).getAttribute("id")) {
    sentList.add(sentence);
}

public static Element getLastChildElement(Node parent) {
    // search for node
    Node child = parent.getLastChild();
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            return (Element) child;
        }
        child = child.getPreviousSibling();
    }
    return null;
}