Trying to build XML file with iterator in java - java

Ive written some code that creates an XML file from my System Properties in java. It works exactly how I want it to but I really (really) dont like how I ended up just using like 5 if statements to get it to work since I noticed none of the properties go beyond 4 delimited substrings anyways.
Id much prefer using an iterator and some kind of hasNext() method to continue appending onto elements until the end of the string but I couldn't work anything out.
I couldn't find a way to append the newest tag onto the last one in a loop/ add the value to the end of the elements.
This is what I currently have as a quick fix to get the program running.
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("JAVA");
doc.appendChild(rootElement);
Iterator it = hm.entrySet().iterator();
while (it.hasNext())
{
Map.Entry entry = (Map.Entry) it.next();
String keyString = (String)entry.getKey();
String val = (String)entry.getValue();
java.util.List<String> sa = Arrays.asList(keyString.split("\\."));
Iterator ait = sa.iterator();
Element tag = doc.createElement((String) ait.next());
rootElement.appendChild(tag);
Element tag2 = null;
Element tag3 = null;
Element tag4 = null;
Element tag5 = null;
while(ait.hasNext())
{
if(ait.hasNext())
{
tag2 = doc.createElement((String)ait.next());
tag.appendChild(tag2);
if(!ait.hasNext())
tag2.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag3=doc.createElement((String)ait.next());
tag2.appendChild(tag3);
if(!ait.hasNext())
tag3.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag4=doc.createElement((String)ait.next());
tag3.appendChild(tag4);
if(!ait.hasNext())
tag4.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag5=doc.createElement((String)ait.next());
tag5.appendChild(tag5);
if(!ait.hasNext())
tag5.appendChild(doc.createTextNode(val));
}
}
}
Transformer transformer = null;
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try
{
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("XMLtester"));
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
} catch (TransformerConfigurationException e)
{
e.printStackTrace();
} catch (TransformerException e)
{
e.printStackTrace();
}
catch(NullPointerException e)
{
System.out.println("ERROR: " + e.toString());
}
System.out.println("File saved!");
If anyone has any ideas on how to make this a little more flexible or elegant so as to take in any number of delimited substrings id appreciate it.

I think this is what you want.
Element destination = rootElement;
Element tag = null;
while (ait.hasNext()) {
tag = doc.createElement((String) ait.next());
destination.appendChild(tag);
destination = tag;
}
destination.appendChild(doc.createTextNode(val));
Example output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<JAVA>
<java>
<runtime>
<name>Java(TM) SE Runtime Environment</name>
</runtime>
</java>
<sun>
<boot>
<library>
<path>/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home/jre/lib</path>
</library>
</boot>
</sun>
<java>
<vm>
<version>23.0-b19</version>
</vm>
</java>
<user>
<country>
<format>GB</format>
</country>
</user>
Full working example:
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class StackOverflow23556822 {
public static void main(String[] args) throws ParserConfigurationException,
TransformerException {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("JAVA");
doc.appendChild(rootElement);
Iterator<?> it = System.getProperties().entrySet().iterator();
while (it.hasNext()) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) it.next();
String keyString = (String) entry.getKey();
String val = (String) entry.getValue();
List<String> sa = Arrays.asList(keyString.split("\\."));
Iterator<?> ait = sa.iterator();
Element destination = rootElement;
Element tag = null;
while (ait.hasNext()) {
tag = doc.createElement((String) ait.next());
destination.appendChild(tag);
destination = tag;
}
destination.appendChild(doc.createTextNode(val));
}
Transformer transformer = null;
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("xml-test.xml"));
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
System.out.println("File saved!");
}
}

Related

XPath assign values to Child of Nodelist from an XML - Java

I have an XML that uses Map* , see below. I want to assign some values to an array (usrHoey).
example.
Assign "String_2" to Variable kode
Assign 2 to Variable prosentsats
How do I accomplish this in java using XPath. See below java code, area to look at is "// usrHoey ************************* ". The previous variable "ankomstDato" work fine.
XML file(xyx.xml)
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="ankomstDato">2020-08-03T09:24:40.486</string>
<map key="historikk">
<array key="usrHoey">
<map>
<string key="kode">string</string>
<number key="prosentsats">0</number>
</map>
</array>
</map>
</map>
Java code that is working well will other simple Nodes.
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//** */
public class SolutionXML2XmlFormat {
//Create Public Variables to store data
//**
public static String ankomstDato_value; //1
//+++
public void Xml2JavaObject(String TheXMLPath){
//read the xml(TheXMLPath) and store values in variables
//This is just an example
ankomstDato_value = "2021-08-03T09:24:40.486";
//Call method to write values
Write2XMLfile();
}
//Modify the existing values in Api_XML_Format.xml
//*
public void Write2XMLfile(){
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
try {
String filepath = "src/main/java/no/difi/oauth2/utils/xyz.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// 1. ankomstDato
Node ankomstDato = (Node) xpath.evaluate("(/map/string[#key='ankomstDato'])[1]", doc, XPathConstants.NODE);
ankomstDato.setTextContent(ankomstDato_value );
// End ankomstDato
// usrHoey **************************
NodeList arrayElements_4 = (NodeList) xpath.evaluate("/map/map/array[#key='usrHoey']/*", doc, XPathConstants.NODESET);
for (int i = 0; i < arrayElements_4.getLength(); i++) {
Node el = arrayElements_4.item(i);
el.setTextContent(pmAnmerkningListe_value[i]);
System.out.println("\n \n");
System.out.println("array element: tag='" + el.getNodeName() + "' text='"
+ el.getTextContent() + "'");
}
// usrHoey
//********** */
//End of historikk
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done Updating The xyz.xml");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
} catch (XPathExpressionException xee) {
xee.printStackTrace();
}
}
}
This is how I did it, it might not be the correct method but it worked for me. I still stand to be corrected by anyone with a better method.
//11. usrHoey **************************
Node usrHoey = (Node) xpath.evaluate("/map/map/array[#key='usrHoey']/*", doc, XPathConstants.NODE);
if(null != usrHoey) {
NodeList nodeList = usrHoey.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
System.out.println("\n");
if(nod.getNodeType() == Node.ELEMENT_NODE){
NodeList arrayElements_11 = (NodeList) xpath.evaluate("/map/map/array[#key='usrHoey']/*", doc, XPathConstants.NODESET);
for (int j = 0; j < arrayElements_11.getLength(); j++) {
//11. Kode
Node kode = (Node) xpath.evaluate("(/map/map/array/map/string[#key='kode'])[1]", doc, XPathConstants.NODE);
kode.setTextContent(usrHoey_kode_value[j]);
// end kode
//12. prosentsats
Node prosentsats = (Node) xpath.evaluate("(/map/map/array/map/string[#key='prosentsats'])[1]", doc, XPathConstants.NODE);
prosentsats.setTextContent(usrHoey_prosentsats_value[j]);
// end prosentsats
}
}
}
}
// usrHoey

Read from folder and update the XML tag value

I have a folder("Container") inside this i have some .txt files which actually contains XML. All files have a common element <Number> which i want to increment by 1 for all the XML files.
any help.
i have done the change for a single .txt file, which is okay:-
package ParsingXML;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class ReadAndModifyXMLFile {
public static final String xmlFilePath = "C:\\Users\\PSINGH17\\Desktop\\testFile.txt";
public static void main(String argv[]) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFilePath);
// Get employee by tag name
//use item(0) to get the first node with tag name "employee"
Node employee = document.getElementsByTagName("employee").item(0);
// update employee , increment the number
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("number");
String str= nodeAttr.getNodeValue();
System.out.println(str);
int val= Integer.parseInt(str);
System.out.println(val);
val=val+1;
System.out.println(val);
String final_value= String.valueOf(val);
System.out.println(final_value);
nodeAttr.setTextContent(final_value);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource, streamResult);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
xml file:-
<?xml version="1.0" encoding="UTF-8" standalone="no"?><company>
<employee number="14">
<firstname>Pranav</firstname>
<lastname>Singh</lastname>
<email>pranav#example.org</email>
<salary>1000</salary>
</employee>
</company>
So this code uses the initial value digits after hash to start the counter.
Then it iterates through all the files in the folder.
The first file will get the initial value, the rest will get incremented values.
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class TestFile {
public static final String xmlFileFolder = "C:\\Rahul\\test";
private static final String initialValue = "450-000-1212";
public static void main(String argv[]) {
int baseValue = Integer.parseInt(getValueAfterLastDash(initialValue));
System.out.println("startValue " + baseValue);
File folder = new File(xmlFileFolder);
for (File file : folder.listFiles()) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
Node employee = document.getElementsByTagName("employee").item(0);
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("number");
System.out.println(getValueBeforeLastDash(initialValue) + baseValue);
nodeAttr.setTextContent(getValueBeforeLastDash(initialValue) + baseValue);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(file);
transformer.transform(domSource, streamResult);
baseValue++;
} catch (Exception ignored) {
}
}
}
private static String getValueAfterLastDash(String initialValue) {
return initialValue.substring(initialValue.lastIndexOf('-') + 1, initialValue.length());
}
private static String getValueBeforeLastDash(String initialValue) {
return initialValue.substring(0, initialValue.lastIndexOf('-') + 1);
}
}

Create XML from a / separated string

Following is a Map element
i need to create a xslt from this.
{ /output1/output1/output1/output13=/input12/bunny,
/output1/output1/output1/output14=/input12/no,
/output1/output1/output13/output12=/input12/ok,
/output1/output1/output13/output16=/input12/honey
}
how should i compare the each element of key element with each element of the next key element?
package mig;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class CreateXSLT {
public static final String xmlFilePath = "D:/xmlfile.xml";
public void createXSLT(ArrayList<String> SourceValues,ArrayList<String> SourceTypes,ArrayList<String> TargetValues,ArrayList<String> TargetTypes,ArrayList<String> Transform)
{
try {
Map<String, String> yourMap = new HashMap<String, String>();
for(int x=0;x<TargetValues.size();x++)
{
yourMap.put(TargetValues.get(x),SourceValues.get(x));
}
Map<String, String> sortedMap = new TreeMap<String, String>(yourMap);
System.out.println(sortedMap);
Set<Entry<String, String>> entires =sortedMap.entrySet();
Set<String> keyset = sortedMap.keySet();
System.out.println(keyset);
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element root = document.createElement("xsl:stylesheet");
document.appendChild(root);
Element root1 = document.createElement("xsl:template");
root.appendChild(root1);
Attr attr = document.createAttribute("match");
attr.setValue("/");
root1.setAttributeNode(attr);
Element empDiffNxt = null;
Element empDiff = null;
int nodeLength = keyset.size();
System.out.println("TARGET sIZE: " + nodeLength);
for(String key : keyset)
{
ArrayList<String> check = new ArrayList<String>();
check.add(key);
String[] Tg = key.split("/");
for (int m=1; m< Tg.length; m++)
{
if( m == 1 )
{
empDiffNxt = document.createElement(Tg[m]);
root1.appendChild(empDiffNxt);
}
else
{
empDiff = document.createElement(Tg[m]);
empDiffNxt.appendChild(empDiff);
empDiffNxt= empDiff;
}
}
Element emp1 = document.createElement("xsl:value-of");
empDiffNxt.appendChild(emp1);
Attr attr1 = document.createAttribute("select");
attr1.setValue(sortedMap.get(key));
emp1.setAttributeNode(attr1);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource, streamResult);
System.out.println("Done creating XML File");
}
catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
this is the code i have written.....
This part is coming as a list inside Targetvalue
/output1/output1/output1/output13
/output1/output1/output1/output14
/output1/output1/output13/output12
/output1/output1/output13/output16
And
/input12/bunny
/input12/bunny
/input12/bunny
/input12/bunny
in the the list Source values
surce value and the target value has link.. means first value of source is connected with first value of target.. 2nd value of source connected with 2nd value of target.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><xsl:stylesheet><xsl:template match="/"><output1><output1><output1><output13><xsl:value-of select="/input12/bunny"/></output13></output1></output1></output1><output1><output1><output1><output14><xsl:value-of select="/input12/no"/></output14></output1></output1></output1><output1><output1><output13><output12><xsl:value-of select="/input12/ok"/><xsl:value-of select="/input12/honey"/></output12></output13></output1></output1></xsl:template></xsl:stylesheet>
this is getting generated.........
but what i want is:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsl:stylesheet>
<xsl:template match="/">
<output1>
<output1>
<output1>
<output13>
<xsl:value-of select="/input12/bunny"/>
</output13>
<output14>
<xsl:value-of select="/input12/no"/>
</output14>
</output1>
<output13>
<output12>
<xsl:value-of select="/input12/ok"/>
</output12>
<output16>
<xsl:value-of select="/input12/honey"/>
</output16>
</output13>
</output1>
</output1>

I can't edit a node content into an XML file with Java

I'm trying to edit an XML file with Java, the thing is that I need to edit the content & replace them by what I want inside
(I want to replace some nodes that are in Deutsh into French
[for expample <fr>DE1</fr> into <fr>FR1</fr>])
I tried to use :
node.setTextContent(Value);
node.setNodeValue(Value);
But it doesn't work at all
Is there any other function that might work in editing these nodes below ?
Here's the code :
for (int i = memory; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if ((langu.equals(node.getNodeName()))) //langu = "fr"
{
test = node.getTextContent();
if(isCorrect()){}
else if ((manualTr.clickCount >= 0)
){
trash = test;
node.setTextcontent(Value);
// node.setNodeValue("Test");
memory += manualTr.clickCount;
manualTr.clickCount -= 1;
}
}
}
And here's the XML code :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<titles>
<tome>
<de>DE1</de>
<fr>DE1</fr>
<en>EN1</en>
</tome>
<valhalla>
<de>DE2</de>
<fr>DE2</fr>
<en>EN2</en>
</valhalla>
<vikings>
<de>DE3</de>
<fr>DE3</fr>
<en>EN3</en>
</vikings>
</titles>
Try this.. I am using setTextContent() to update a node value.
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* #author JayaPrasad
*
*/
public class ParseXml {
public static void main(String[] args) {
System.out.println("Started XML modification");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document xmlDoc;
xmlDoc = docBuilder.parse(new File("sample.xml"));
NodeList nodes = xmlDoc.getElementsByTagName("fr");
for (int i = 0, length = nodes.getLength(); i < length; i ++) {
((Element)nodes.item(i)).setTextContent("Modified");
}
xmlDoc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(xmlDoc);
StreamResult result = new StreamResult(new File("sample.xml"));
transformer.transform(domSource, result);
System.out.println("Modification Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Java overwriting files with stream result

I created a simple class to create an XML document.
However, if I call the method more than once while creating a document of the same name the file does not overwrite.
How could I make the class automatically overwrite existing files of the same name?
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLCreater {
public static void CreateXMLDoc(String name, String root, String[] elements, String[] children) throws TransformerConfigurationException {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(root);
doc.appendChild(rootElement);
for (int i = 0; i < elements.length; i ++) {
Element element = doc.createElement(elements[i]);
element.appendChild(doc.createTextNode(children[i]));
rootElement.appendChild(element);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
File dir = new File(System.getProperty("user.dir"));
StreamResult result = new StreamResult(new File(dir + "\\XML\\" + name + ".xml"));
transformer.transform(source, result);
}
catch(ParserConfigurationException pce){
pce.printStackTrace();
} catch(TransformerException tfe) {
tfe.printStackTrace();
}
}
}
I executed your code with the following statements:
public static void main (String[] args)
{
XMLCreater x = new XMLCreater();
String[] s = {"A","B","C"};
try
{
x.CreateXMLDoc("k","root",s,s);
x.CreateXMLDoc("k","root",s,s);
x.CreateXMLDoc("fakih","root",s,s);
}
catch (TransformerConfigurationException exception)
{ exception.printStackTrace(); }
}
And it nicely overwrites the existing files, no problems about overwriting, check it yourself.
I'll be honest here... I'm not able to replicate your problem. It works fine for me when I run this program multiple times in a for loop. Are you sure you didn't accidentally open the result file, thus locking it, before running your program?
If you are concerned of having multiple threads running your program at the same time, perhaps you can apply a synchronized block to prevent two threads trying to write the same file, like this:-
...
synchronized (XMLCreater.class) {
StreamResult result = new StreamResult(new File(dir + "\\XML\\" + name + ".xml"));
transformer.transform(source, result);
}

Categories