my code just add new Node and child Nodes to my xml file , and then print it as output .
Now How I can save the xml file again after these adds
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("src\\xpath\\Products.xml");
//make new node (product)
Element newproduct = document.createElement("product");
document.getDocumentElement().appendChild(newproduct);
//add attribute to the new product
newproduct.setAttribute("id", id);
//add name to the new product
Element newename = document.createElement("name");
newproduct.appendChild(newename);
newename.appendChild(document.createTextNode(name));
//add price to the new product
Element neweprice = document.createElement("price");
newproduct.appendChild(newename);
neweprice.appendChild(document.createTextNode(price));
// print XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
StreamResult console = new StreamResult(System.out);
transformer.transform(source, console);
System.out.println("\nNew Product added to product.xml.");
} catch (Exception e) {
System.err.println(e.getMessage());
}
In place of printing to console
StreamResult console = new StreamResult(System.out);
save to file
StreamResult result = new StreamResult(new File("src\\xpath\\Products.xml"));
transformer.transform(source, result);
Related
I added node in a existing xml file located in /data/data.my.package.app/files/file.xml and I just want to save the file but I didn't find out.
I tried this function seen in an other post :
private void save(Document newDoc) throws Exception{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new File(context.getFilesDir().getAbsolutePath() + "/file.xml"));
Source source = new DOMSource(newDoc);
transformer.transform(source, result);
}
But I get an null pointer exception on tranformer.transform() ... This is how I initialise my Document file.
FileInputStream is = new FileInputStream(context.getFilesDir().getAbsolutePath() + "/file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Thanks a lot for the help
A.D
The file cannot be new.
Must be already present:
StreamResult result =
new StreamResult(new File(context.getFilesDir().getAbsolutePath() + "/file.xml"));
for me this work:
//save the doc as string in a text file with the same name (extension .xml)
save(this, body, dir, FILENAME_XML);
//apply the transformer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory_p.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(
new File(dir+File.separator+FILENAME_XML));
transformer.transform(source, result);
the file xml is produced.
what's wrong? this code dont save and dont show error
this code :
read file menuAdm.xml
treat that Document
save treated content in another xml (menuAdm2.xml)
DocumentBuilder dBuilder = null;
try {
dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = dBuilder.parse(new File("/seguranca/menuAdm.xml"));
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
Element root = doc.getDocumentElement();
// do treatment of doc (menuAdm.xml)
// save into another file (menuAdm2.xml)
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/seguranca/menuAdm2.xml") );
transformer.transform(source, result);
} catch (Exception e) {
System.out.println("Error to save file " + e.getMessage());
}
I am using the follwing code to change a xml document:
DocumentBuilderFactory fty1 = DocumentBuilderFactory.newInstance();
fty1.setNamespaceAware(true);
DocumentBuilder builder1 = fty1.newDocumentBuilder();
ByteArrayInputStream bais1 = new ByteArrayInputStream(tr1.getBytes());//tr1=xml string
Document xmldoc1=builder1.parse(bais1);
xmldoc1.getElementsByTagName("userID").item(0).setTextContent("123123132");
The xmldoc1 contains the changed form. Now how convert it to a string so that the new doument can be passed to others.
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(xmldoc1);
transformer.transform(source, result);
String xmlString = sw.toString();
i would like to append a new tag with some attributes with those values in to xml file and save that xml file through my application.i have written a method for append a new tag as child to xml file which is available in sdcard of android emulator.the following method for append a new tag as follows
public void appendTag(){
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("/sdcard/sample.xml"));
Node node = doc.getElementsByTagName("earth").item(0);
//append a new node to earth
Element newelmnt = doc.createElement("new");
newelmnt.appendChild(doc.createTextNode("this is a text"));
node.appendChild(newelmnt);
}
catch (Exception e) {
e.printStackTrace();
}
}
after execution of this method i can't able to find a new tag in xml file.
could please any one help on how to append new tag as child in xml file and how save the modification?
if i uses TransformerFactory i am getting error as
ERROR/AndroidRuntime(13479): java.lang.VerifyError: com.sample.xmlapp.DOMClass
i have used as follows
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/sdcard/sample.xml"));
transformer.transform(source, result);
Your in memory document will be changed, but you will need to write it to a file again.
Try adding this for writing the document to the file again:
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/sdcard/sample.xml"));
transformer.transform(source, result);
I am looking for something like this :
<Node1>
<Child2 attr1="abc">
<Child3 attr2="xyz">
<Node1>
From Node1 , I want to get the contents inside the node as text. The output I want is
"<Child2 attr1="abc"><Child3 attr2="xyz">"
//Parse the input document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("yourfile.xml"));
//Set up the transformer to write the output string
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
//Find the first child node
NodeList nl = doc.getDocumentElement().getChildNodes();
DOMSource source = null;
for(int x = 0;x < nl.getLength();x++)
{
Node e = nl.item(x);
if(e instanceof Element)
{
source = new DOMSource(e);
break;
}
}
transformer.transform(source, result);
System.out.println(sw.toString());
}
}
See this question with other possible answers.