2016-04-26 3 views
0

私は解析したいXMLレスポンスを持っています。そして私は、私が知りたいのですが、それはしかし、働いているように見える、私は親ノード親ノードの最後の子に達したかどうかをチェックする方法Java

XMLのlastChild達したか(Javaコードで)私が知っていることができます。

<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> 

をコード:現在のノードがテキストID = 3である例えば

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

は、どのように私は、これは確かに親ノードの文の最後の子であるかを確認することができますか?このようにして、構築された文をリストに追加して後で読むことができます。

この方法では、私が送信され、リスト内の次の文字列の項目があります:

あなたは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> 

お知らせ、構造が考慮に異なる構造を取るためにどのように...若干異なっています。私の解決策は、ここで働いているようには見えません。なぜなら、Sentenceの子の最後の子に属性がないからです。おそらくXpathを使う方が良いでしょうか?

+0

これは正規表現と関係があるのでしょうか? – Laurel

+0

これはスタックオーバーフローの推奨事項でした:) –

+0

あなたの質問に関連していない限り、タグを追加しないでください。 – Laurel

答えて

0

これは私の問題で解決するようです。私は最後の兄弟を探し、現在のノード属性値と最後のノード属性値を比較します。同じ場合は、作成された文を文字列リストに追加します。

コード:

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