2016-04-26 47 views
0

我有我想要解析的XML響應。而我似乎也不過工作,我想知道,如何(在Java代碼),我可以知道我已經達到了父節點如何檢查您是否已到達父節點的最後一個孩子Java

XML的lastChild:

<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); 
} 

例如,噹噹前節點是文章ID = 3,我如何檢查,看看這確實是父節點句子的最後一個孩子?這樣我可以將構造的句子添加到列表中並在稍後閱讀。

這樣,我將在發送列表中的以下字符串項:

你是高大的,因爲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?

+0

這是什麼都用正則表達式來呢? – Laurel

+0

這是一個stackoverflow推薦:) –

+0

不要添加標籤,除非它們與你的問題相關。 – Laurel

回答

0

這似乎解決了我的問題。我找到最後一個兄弟節點,然後只比較當前的節點屬性值和最後一個節點屬性值,如果它們相同,則將構造的句子添加到字符串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; 
} 
相關問題