我需要在android中编写XML文件并将其替换为新文件。代码工作正常但在我的XML文件中没有任何改变。
任何想法?
try{
FileOutputStream fOut = openFileOutput("/data/data/test.fileshow/files/Landmarks.xml", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
String filepath = "Landmarks.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
Element Row, Longitude, Latitude, Title, Category, Rating;
Node staff = doc.getElementsByTagName("Root").item(0);
Row=doc.createElement("Row");
Longitude=doc.createElement("Longitude");
Longitude.appendChild(doc.createTextNode("555"));
Row.appendChild(Longitude);
Latitude=doc.createElement("Latitude");
Latitude.appendChild(doc.createTextNode("ABCCamera"));
Row.appendChild(Latitude);
Title=doc.createElement("Title");
Title.appendChild(doc.createTextNode("title"));
Row.appendChild(Title);
Category=doc.createElement("Category");
Category.appendChild(doc.createTextNode("category"));
Row.appendChild(Category);
Rating=doc.createElement("Rating");
Rating.appendChild(doc.createTextNode("rating"));
Row.appendChild(Rating);
staff.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);
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)
我在编写DOM文档时遇到了问题,这让我走上了正确的道路。从您的代码中,我必须将OutputStreamWriter绑定到StreamResult。
实例化后:
StreamResult result = new StreamResult(new File(filepath));
请致电以下人员:
result.setWriter(osw);
在执行转换之前。这对我有用。