我已经提供了我正在使用的xml样本来获取食物项目列表并将其扩展到列表视图。我尝试在运行时将该项目添加到我的xml文件中我得到了url格式错误的例外。可能我给的路径是无效的。我把我的xml放在package / res / raw / testcalory.xml.kindly帮助中。
EXCEPTION:12-26 14:35:58.516:WARN / System.err(11597):java.net.MalformedURLException:找不到协议:testcalory.xml
//sample xml
<?xml version="1.0"?>
<company>
<Row>
<Item_Name>Aam Ras </Item_Name>
<CalorieContentPerGram>1.12</CalorieContentPerGram>
</Row>
<Row>
<Item_Name>Akuri </Item_Name>
<CalorieContentPerGram>1.62</CalorieContentPerGram>
</Row>
<Row>
<Item_Name>Almond ICC </Item_Name>
<CalorieContentPerGram>5.35</CalorieContentPerGram>
</Row>
<Row>
<Item_Name>Almond Milkshake </Item_Name>
<CalorieContentPerGram>1.16</CalorieContentPerGram>
</Row>
</company>
//sample code
private void addItem() {
// TODO Auto-generated method stub
try{
FileOutputStream fOut = openFileOutput("testcalory", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
String filepath = "testcalory.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
org.w3c.dom.Element Row;
org.w3c.dom.Element Item_Name;
org.w3c.dom.Element CalorieContentPerGram;
Node company = doc.getElementsByTagName("company").item(0);
Row=doc.createElement("Row");
Item_Name=doc.createElement("Item_Name");
Item_Name.appendChild(doc.createTextNode("hulala"));
Row.appendChild(Item_Name);
CalorieContentPerGram=doc.createElement("CalorieContentPerGram");
CalorieContentPerGram.appendChild(doc.createTextNode("556"));
Row.appendChild(CalorieContentPerGram);
company.appendChild(Row);
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
result.setWriter(osw);
osw.flush();
osw.close();
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(TransformerException tfe){
tfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(SAXException sae){
sae.printStackTrace();
}
}
答案 0 :(得分:1)
在你的情况下,它将无法正常工作。您应该阅读有关xml解析器和编写器的信息。例如,here。
至于我,我曾经使用Simple XML。它非常简单,允许您从应用程序中解析和创建xml文件。