DOM XML解析器JAVA,相同的标签
问题描述:
我有这个xml文件,它有不同数量的相同的命名标签。我怎么能得到子元素的数量和它的价值。DOM XML解析器JAVA,相同的标签
<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选项 QuestionText 1:ABC?选项1:A1 - XYZ 选项2:A2 - WXY选项3:A2 - HJK
ID:1有3个QuestionText和0个选项 QuestionText 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());
}
}
答
什么是getTagValue()
后?
无论如何,这是针对Java中DOM解析器的最佳教程(How to read XML file in Java)。看看这个
下面是从链接
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();
}
@hilal
getTagValue()
...谢谢..well..i使用的教程它的自我,我已经明白它是如何works..but我问题是别的。请再次看看它 – 2011-02-12 17:56:42