0
我想製作一個XML解析器。但是,下面的代碼只是給出了空白輸出。 getElementValue()函數中的「heyya」消息正在打印,它告訴空字符串被返回。請幫忙。在android中解析XML空白字符串
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLParser {
public Document getDomElement(String xml)
{
Document doc=null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
}catch (ParserConfigurationException e){
System.out.println(e.getMessage());
return null;
} catch(SAXException e){
System.out.println(e.getMessage());
return null;
} catch(IOException e){
System.out.println(e.getMessage());
return null;
}
return doc;
}
public String getValue(Element item, String str)
{
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue(Node elem)
{
Node child;
if(elem!=null){
if(elem.hasChildNodes()){
for(child=elem.getFirstChild(); child!=null; child = child.getNextSibling()){
if(child.getNodeType() == Node.TEXT_NODE){
return child.getNodeValue();
}
}
}
}
//System.out.println("heyya");
return "";
}
}
class createData
{
static final String KEY_ID = "id"; //parent node
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
public void createArrayList()
{
//ArrayList<HashMap<String, String>> userData = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
//obtain xml as string here
String xml="<menu>\n\t<item>\n\t\t<id>1</id>\n\t\t<name>Margherita</name>\n\t\t<cost>155</cost>\n\t\t<description>Single cheese topping</description>\n\t</item></menu>\n";
Document doc = parser.getDomElement(xml);
NodeList node_L = doc.getElementsByTagName(KEY_ID);
for(int i=0; i<node_L.getLength(); i++)
{
//HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)node_L.item(i);
String name = parser.getValue(e, KEY_NAME);
String cost = parser.getValue(e, KEY_COST);
String description = parser.getValue(e, KEY_DESC);
System.out.println(name+" "+cost+" "+description);
//map.put(KEY_NAME, name);
//map.put(KEY_COST, cost);
//map.put(KEY_DESC, description);
//userData.add(map);
}
System.out.println("hello pop!");
//System.out.println(userData.get(0));
}
public static void main(String args[])throws IOException
{
createData ob =new createData();
ob.createArrayList();
}
}
他在3個「ifs」和1個「for」中有一個'return'。它不會一直執行。 – SudoRahul 2013-03-02 10:05:23
@ R.J需要更多咖啡。我在下一個小時停留在這裏;) – Simon 2013-03-02 10:08:56