append node to an xml in Java - java

I can't append correctly some info to my xml file. That's the scrivi function
public String scrivi (Document doc, File dest)
{
try
{
DOMSource sorgente = new DOMSource (doc);
StreamResult sr = new StreamResult (dest);
TransformerFactory tf =
TransformerFactory.newInstance();
Transformer transf = tf.newTransformer();
transf.transform (sorgente, sr);
return "Tutto ok";
}
catch (TransformerConfigurationException tce)
{
System.out.println(tce.getMessage());
return "<h1> Config </h1>";
}
catch (TransformerException te)
{
System.out.println(te.getMessage());
return "<h1> Transformer Errore </h1>";
}
}
and tath is my code:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(getClass().getResourceAsStream("/azioni.xml"));
Element root = document.getDocumentElement();
Element new_azione = document.createElement("azione");
Element id = document.createElement("id_azione");
id.setTextContent(id_azione);
Element nome = document.createElement("nome_azione");
nome.setTextContent(nome_azione);
Element prezzo_a = document.createElement("prezzo");
prezzo_a.setTextContent(prezzo);
new_azione.appendChild(id);
new_azione.appendChild(nome);
new_azione.appendChild(prezzo_a);
document.getDocumentElement().appendChild(new_azione);
String nomexmlOut="/azioni.xml";
File filedest = new File(nomexmlOut);
out.println(this.scrivi(document, filedest));
}
I get the error Transformer Errore ... how can I solve? what's Wrong?
* UPDATE *
Error Info
java.io.FileNotFoundException: /azioni.xml (Permission denied)

Hard to tell without actual exception trace or message, but my guess is that your problem is the ouput stream.
File("/azioni.xml");
is not the same as
getClass().getResourceAsStream("/azioni.xml")
Try with directing the output to system out and see if it works. i.e. declare scrivi
public String scrivi (Document doc, OutputStream out)
and call it with
scrivi(document, System.out);
UPDATE:
To write to the same file location, try something like this (untested)
File out = new File(getClasss().getResource("...").getFile());
and make sure that you close the input stream that you originally read from, before trying to write.

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"

Saving a XML Document in another xml file

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

Modified XML file not saving java

I am making a web application, and I need to make a log. I am storing this log as an xml file.
These are my paths:
log.xml -> org.codealizer.quizme.resources
Servlet -> org.codealizer.quizme.servlets
When my application runs, it gives me a success result, but the xml file is not modified.
This is my code to modify the xml file:
private void createLog(HttpServletRequest request,
HttpServletResponse response, PrintWriter out) {
String ipAddress = request.getRemoteAddr();
int port = request.getRemotePort();
String clientInformation = request.getHeader("user-agent");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = dBuilder.parse(getClass().getResourceAsStream(
"/org/codealizer/quizme/resources/log.xml"));
doc.getDocumentElement().normalize();
Node log = doc.getFirstChild();
Element item = doc.createElement("item");
Element time = doc.createElement("time");
time.appendChild(doc.createTextNode("" + System.currentTimeMillis()));
item.appendChild(time);
Element access = doc.createElement("access");
access.appendChild(doc.createTextNode(getClass().getName()));
item.appendChild(access);
Element address = doc.createElement("address");
address.appendChild(doc.createTextNode(ipAddress + ":" + port));
item.appendChild(address);
Element client = doc.createElement("client");
client.appendChild(doc.createTextNode(clientInformation));
item.appendChild(client);
log.appendChild(item);
// Update
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(getClass().getResource(
"/org/codealizer/quizme/resources/log.xml").getFile());
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (SAXException | IOException | ParserConfigurationException
| TransformerException e) {
out.println(e.getMessage());
}
This is my current log.xml file
<?xml version="1.0" encoding="UTF-8"?>
<log></log>
Could someone please help me fix this issue? Thx a lot :)

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

Bad Characters when parsing GML in Java

I'm using the org.w3c.dom package to parse the gml schemas (http://schemas.opengis.net/gml/3.1.0/base/).
When I parse the gmlBase.xsd schema and then save it back out, the quote characters around GeometryCollections in the BagType complex type come out converted to bad characters (See code below).
Is there something wrong with how I'm parsing or saving the xml, or is there something in the schema that is off?
Thanks,
Curtis
public static void main(String[] args) throws IOException
{
File schemaFile = File.createTempFile("gml_", ".xsd");
FileUtils.writeStringToFile(schemaFile, getSchema(new URL("http://schemas.opengis.net/gml/3.1.0/base/gmlBase.xsd")));
System.out.println("wrote file: " + schemaFile.getAbsolutePath());
}
public static String getSchema(URL schemaURL)
{
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(IOUtils.toString(schemaURL.openStream()))));
Element rootElem = doc.getDocumentElement();
rootElem.normalize();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream xmlOutStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(xmlOutStream);
transformer.transform(source, result);
return xmlOutStream.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
I'm suspicious of this line:
Document doc = db.parse(new InputSource(
new StringReader(IOUtils.toString(schemaURL.openStream()))));
I don't know what IOUtils.toString does here but presumably it's assuming a particular encoding, without taking account of the XML declaration.
Why not just use:
Document doc = db.parse(schemaURL.openStream());
Likewise your FileUtils.writeStringToFile doesn't appear to specify a character encoding... which encoding does it use, and why encoding is in the StreamResult?

Categories