I've been fiddling with this for over twenty minutes and my Google-foo is failing me.
Let's say I have an XML Document created in Java (org.w3c.dom.Document):
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("RootElement");
Element childElement = document.createElement("ChildElement");
childElement.appendChild(document.createTextNode("Child Text"));
rootElement.appendChild(childElement);
document.appendChild(rootElement);
String documentConvertedToString = "?" // <---- How?
How do I convert the document object into a text string?
public static String toString(Document doc) {
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
}
You can use this piece of code to accomplish what you want to:
public static String getStringFromDocument(Document doc) throws TransformerException {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
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.
I have an xml file, and sometimes I have to delete some nodes.
This is my code:
String xmlProduct = ""; //my xml above
if(!xmlProduct.equals("")){
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlProduct));
Document dom;
DocumentBuilderFactory dbf = (DocumentBuilderFactory) DocumentBuilderFactory.newInstance();
DocumentBuilder db = (DocumentBuilder) dbf.newDocumentBuilder();
dom = db.parse(is);
dom.normalize();
//delete property
NodeList nodoProperty = dom.getDocumentElement().getElementsByTagName("Property");
for(int i=0; i<nodoProperty.getLength(); i++){
Node nodoBorrar = nodoProperty.item(i);
nodoRaizXML.item(0).removeChild(nodoBorrar);
}
}
//Convert to xml format
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(dom), new StreamResult(writer));
This is an example of my xml:
<Deal>
<SelectedDeal>+1</SelectedDeal>
</Deal>
<Property>
<PropertyId>8215</PropertyId>
<HPIValueChanged>1</HPIValueChanged>
</Property>
<FundBooking>
<ProductCode>J128R?</ProductCode>
<ControlNumber> </ControlNumber>
</FundBooking>
And this is what I got when executing:
<Deal>
<SelectedDeal>+1</SelectedDeal>
</Deal>
<FundBooking>
<ProductCode>J128R?</ProductCode>
<ControlNumber> </ControlNumber>
</FundBooking>
the tag is deleted, but I need to delete its space in the file.
How can I do this
This is the quick & dirt solution :
xmlProduct = xmlProduct.replaceAll("\n", "").replaceAll("\r", "");
//...
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
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
I've developed a method to insert a new element in a XML File. I'm testing it reading the first element Usuario of the input file and appending it at the end.
Input:
<Usuarios>
<Usuario>
<id>identificador</id>
<email>nn#gmail.com</email>
<rol>profesor</rol>
<alta>01/01/2012</alta>
<baja>30/08/2021</baja>
</Usuario>
<Usuario>
<id>00000000H</id>
<email>pertur#gmail.com</email>
<rol>profesor</rol>
<alta>01/01/2012</alta>
<baja>30/08/2021</baja>
</Usuario>
<Usuario>
<id>970104</id>
<email>kk#gmail.com</email>
<rol>alumno</rol>
<alta>01/01/2012</alta>
<baja>30/08/2021</baja>
</Usuario>
</Usuarios>
Output:
<Usuarios>
<Usuario>
<id>identificador</id>
<email>nn#gmail.com</email>
<rol>profesor</rol>
<alta>01/01/2012</alta>
<baja>30/08/2021</baja>
</Usuario>
<Usuario>
<id>00000000H</id>
<email>pertur#gmail.com</email>
<rol>profesor</rol>
<alta>01/01/2012</alta>
<baja>30/08/2021</baja>
</Usuario>
<Usuario>
<id>970104</id>
<email>kk#gmail.com</email>
<rol>alumno</rol>
<alta>01/01/2012</alta>
<baja>30/08/2021</baja>
</Usuario>
<Usuario>
<id>identificador</id>
<email>nn#gmail.com</email>
<rol>profesor</rol>
<alta>01/01/2012</alta>
<baja>30/08/2021</baja>
</Usuario>
</Usuarios>
What am I doing bad? There are two issues:
1.- The elements in the input are not properly indented y the output file. The transformer don't reindents all the registers?
2.- The new element is properly indented, but the new instance of not.
Ideas?
source:
public void almacenarUsuario(UsuarioNegocio usuario) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File(directorio + "personas.xml"));
Element nUsuario = (Element) doc.getElementsByTagName("Usuarios").item(0);
Node node = doc.createElement("Usuario");
nUsuario.appendChild(node);
Element nid = doc.createElement("id");
nid.appendChild(doc.createTextNode(usuario.getIdUsuario()));
node.appendChild(nid);
Element nemail = doc.createElement("email");
nemail.appendChild(doc.createTextNode(usuario.getEmail()));
node.appendChild(nemail);
Element nrol = doc.createElement("rol");
nrol.appendChild(doc.createTextNode(usuario.getRol()));
node.appendChild(nrol);
Element nalta = doc.createElement("alta");
nalta.appendChild(doc.createTextNode(usuario.getFecha_alta()));
node.appendChild(nalta);
Element nbaja = doc.createElement("baja");
nbaja.appendChild(doc.createTextNode(usuario.getFecha_baja()));
node.appendChild(nbaja);
// Formatter //
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", new Integer(25));
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount","4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/opt/icxp1/Temporal/jose/personal/nuevo.xml"));
transformer.transform(source, result);
}
Before transforming,
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
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();