Saving a XML Document in another xml file - java

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());
}

Related

I want append data at the end of text file .xml . I use textfield to SetTextContent . Now I want add next tag on file xml

private void bt_create_xml(ActionEvent e) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("University");
doc.appendChild(rootElement);
Element staff = doc.createElement("student");
// add staff to root
rootElement.appendChild(staff);
// add xml attribute
staff.setAttribute("rollno", tf_input_id.getText());
Element name = doc.createElement("fullname");
name.setTextContent(tf_input_fullname.getText());
staff.appendChild(name);
Element code = doc.createElement("code");
code.setTextContent(tf_input_code.getText());
staff.appendChild(code);
Element birthday = doc.createElement("birthday");
birthday.setTextContent(tf_input_birth.getText());
staff.appendChild(birthday);
Element department = doc.createElement("department");
department.setTextContent(tf_input_depart.getText());
staff.appendChild(department);
Element address = doc.createElement("address");
address.setTextContent(tf_input_add.getText());
staff.appendChild(address);
try{
writeXml(doc, System.out);
FileOutputStream out=new FileOutputStream("D:\\JAVA\\XML-CUOIKY\\XML.xml");
writeXml(doc,out);
}catch (Exception exx){
exx.printStackTrace();
}
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
}
private static void writeXml(Document doc,
OutputStream output)
throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// pretty print
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
}
"I want append data at the end of text file .xml . I use textfield to SetTextContent . Now I want add next tag on file xml"

Save modified xml into internal storage Android

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.

better approach to creat an xml in java

I am creating xml through dom parser as shown below in a method Please advise is there any other better approach to achieve the same in java as dom parser is considered to be loading the memory that why i was looking for better approach
String xmlString = null ;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("yyyyMMdd");
Element rootElement = doc.createElement("abcmail");
doc.appendChild(rootElement);
Element invoiceReferenceNotificationMessage = doc.createElement("invoiceReferenceNotificationMessage");
rootElement.appendChild(invoiceReferenceNotificationMessage);
Element ceReference = doc.createElement("ceReference");
ceReference.appendChild(doc.createTextNode(irm.getceReference()));
ceReferenceNotificationMessage.appendChild(ceReference);
Element RBSReference = doc.createElement("ABSReference");
ABSReference.appendChild(doc.createTextNode(irm.getABSReference()));
ceReferenceNotificationMessage.appendChild(ABSReference);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, result);
writer.flush();
xmlString = writer.toString();
return xmlString;
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
return xmlString;
}
The better way is using JAXB.
You can see an example here

Create namespace in dom element issue

Im trying to create XML document with DOM APi's and when i use the following code I got the
expect result
Element rootTreeNode = document.createElementNS("http://schemas.microsoft.com/ado/2007","ex" + ":Ex")
this is the output with tags in output console
ex:Ex Version="1.0" xmlns:ex="http://schemas.microsoft.com/ado/2007"/
Now I want to add to this element the following
**xmlns:gp**="http://www.pst.com/Protocols/Data/Generic"
and I dont succeed with the xmlns:gp i have tried to use
the like the following
rootTreeNode.setAttributeNS("xmlns" ,"gp","http://www.pst.com/Protocols/Data/Generic")
and i have got it like the folloing
**xmlns:ns0="xmlns"** **ns0:gp**="http://www.pst.com/Protocols/Data/Generic"
and if put null in the first parameter
rootTreeNode.setAttributeNS(null ,"gp","http://www.pst.com/Protocols/Data/Generic")
I get just gp with the URL without the xmlns .
what am i doing wrong here ?
Thanks!!!
Complete test:
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElementNS("http://schemas.microsoft.com/ado/2007","ex" + ":Ex");
root.setAttributeNS("http://www.w3.org/2000/xmlns/" ,"xmlns:gp","http://www.pst.com/Protocols/Data/Generic");
doc.appendChild(root);
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
System.out.println("Xml:\n\n" + xmlString);

how to append tags in xml in android? and how save that xml file?

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);

Categories