私は、さまざまな数の同じ名前のタグを持つこのxmlドキュメントを持っています。子要素の数とその値を取得するにはどうすればよいですか。
<Question>
<QuestionText>ABC?</QuestionText>
<Option>A1 - XYZ</Option>
<Option>A2 - WXY</Option>
<Option>A2 - HJK</Option>
<ID>1</ID>
</Question>
<Question>
<QuestionText>ERY?</QuestionText>
<QuestionText>NNN?</QuestionText>
<QuestionText>KKKK?</QuestionText>
<ID>2</ID>
</Question>
出力は次のようになります...
ID:2 1 つの QuestionText と 3 つの Option QuestionText 1:ABC がありますか? オプション 1:A1 - XYZ オプション 2:A2 - WXY オプション 3:A2 - HJK
ID:1 QuestionText が 3 つ、オプション QuestionText が 0 の場合 1.ERY? QuestionText 2.NNN? QuestionText 3.KKKK?
試しましたが、これによりエラーが発生します
Element eElement = (Element) nNode;
for(int i=0;i<eElement.getChildNodes().getLength();i++){
System.out.println("NodeName:"+eElement.getNodeName());
System.out.println("Tag value:"+getTagValue("QuestionText",eElement));
System.out.println("Tag value:"+getTagValue("Option",eElement));
}
private static String getTagValue(String sTag, Element eElement){
NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
いくつかの調査を行った後、解決策を見つけました
Element eElement = (Element) nNode;
getTagValue("QuestionText",eElement);
getTagValue("Option",eElement);
private static void getTagValue(String sTag, Element eElement){
NodeList nlList = eElement.getElementsByTagName(sTag);
System.out.println("Size of nodelist:"+nlList.getLength());
for(int i=0;i<nlList.getLength();i++){
NodeList kList= eElement.getElementsByTagName(sTag).item(i).getChildNodes();
Node kValue = (Node) kList.item(0);
System.out.println("Node Value:"+kValue.getNodeValue());
}
}