I am reading a xml file from the SD card. Here I want to change the values of the XML file and I want to save the file to the sd card..
My code is like below.... Please guide me how to save XML file to the sd card after updating the values..
public void modifyNodeval(){
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("/sdcard/sss.xml"));
//Get the staff element by tag name directly
Node nodes = doc.getElementsByTagName("Employee").item(0);
//loop the staff child node
NodeList list = nodes.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
//get the salary element, and update the value
if("Emp_Name".equals(node.getNodeName())){
开发者_JS百科 node.setNodeValue("795796");
}
}
Something like this:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(file);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
how to modify xml node value?
This method writes a DOM document to a file on the SD Card If you want to test this in the emulator, make sure your AVD image is setup with an SD Card image (done during image creation).
public static void writeXmlFile(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
File file new File(Environment.getExternalStorageDirectory(),fileName);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
// handle exception
} catch (TransformerException e) {
// handle exception
}
}
精彩评论