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");
Related
I create entity reference with EntityReference ent = doc.createEntityReference(txt). Then I add it to the node: node.appendChild(ent); and the txt is like "lt". So, I expect to see < in my XML file. But all entity references are missing. Other elements are added and shown well, but not EntityReference.
XML is created as:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
dumping to the file:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new StringWriter());
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
return xmlString;
The result XML has a standard header:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
...
Where can be a problem?
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");
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);
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();
}