我正在尝试解析XML文件,如下所示
<Subject>
<chapter>
<Question>abc</Question>
<answer>avksn</answer>
</chapter>
<chapter>
<Question>def</Question>
<answer>avksn</answer>
</chapter>
<chapter>
<Question>ccsv</Question>
<answer>avksn</answer>
</chapter>
</Subject>
在这个我能够计算章节的数量。章的数量等于问答的数量。我还在我的布局中放置了一个名为ok的按钮。
现在我想显示第一个问题,点击确定后我想显示第二个问题,直到结束。当我到达最后一个问题时,我想进入一项新活动。
如何执行此操作,请帮助我
答案 0 :(得分:1)
将XML读入文档(v = xml字符串)
public Document XMLfromString(){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(v));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
然后得到这样的元素:
/** Returns element value
* @param elem element (it is XML tag)
* @return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
使用方法:
Document doc = x.XMLfromString();
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", x.getValue(e, "orgid"));
map.put("bedrijf", x.getValue(e, "naam"));
map.put("plaats", x.getValue(e, "plaats"));
mylist.add(map);
}
答案 1 :(得分:1)
将xml读入InputStream,然后:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse([the InpuTstream]);
然后你可以使用doc:
if(doc.getElementsByTagName("GeometryCollection").getLength()>0){
org.w3c.dom.Node parent_node = doc.getElementsByTagName("GeometryCollection").item(0);
NodeList nl = parent_node.getChildNodes();
for(int i = 0;i<nl.getLength();i++){
...