Sample XML which i have to generate using JAVA
sense
168
192.168.140.150
002EC0FEFF83EA97
Code Used I have written so far
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class SampleCode {
public static final String xmlFilePath = "C:\\Users\\harsh.sharma\\Desktop\\Sense Performance\\Generated\\xmlfile.xml";
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
try {
String cid_Value="168";
String ip_Value="192.168.140.150";
String id_Value="002EC0FEFF83EA97";
String sensorsid_Value="002EC0FEFF8FFF27";
String desc_Value=" ";
String batt_Value="6.60";
String sig_Value="-55";
String scount_Value="0";
String rdate_Value="15/05/2015 21:47:04";
DateFormat dateFormat = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss");
//get current date time with Date()
#SuppressWarnings("deprecation")
Calendar cal = Calendar.getInstance();
String mdate_Value=dateFormat.format(cal.getTime());
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
//root element
Element root = document.createElement("msgs");
document.appendChild(root);
//msg element
Element msg = document.createElement("msg");
root.appendChild(msg);
//type element
Element type = document.createElement("type");
msg.appendChild(type);
type.setTextContent("Sense");
//cid element
Element cid = document.createElement("cid");
msg.appendChild(cid);
cid.setTextContent(cid_Value);
//ip element
Element ip = document.createElement("ip");
msg.appendChild(ip);
ip.setTextContent(ip_Value);
Element errs = document.createElement("errs");
msg.appendChild(errs);
//id element
Element id = document.createElement("id");
msg.appendChild(id);
id.setTextContent(id_Value);
//sensors element
Element sensors = document.createElement("sensors");
msg.appendChild(sensors);
//Sensor element
Element sensor = document.createElement("sensor");
//sensors.appendChild(sensor);
sensor.setAttribute("sensorsid",sensorsid_Value);
sensor.setAttribute("desc",desc_Value);
sensor.setAttribute("batt",batt_Value);
sensor.setAttribute("sig", sig_Value);
sensor.setAttribute("scount",scount_Value);
sensor.setAttribute("rdate",rdate_Value);
sensor.setAttribute("mdate",mdate_Value);
sensors.appendChild(sensor);
// create the xml file
//transform the DOM Object to an XML File
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
// If you use
// StreamResult result = new StreamResult(System.out);
// the output will be pushed to the standard output ...
// You can use that for debugging
transformer.transform(domSource, streamResult);
System.out.println("Done creating XML File");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
I want it should give me multiple rows under the sensor Element, I want to write the loop that I can generate multiple data for the sensor Element
Related
I am trying to change the PlannedDuration of Activity A04 but I have not been able to see the changes in the XML file. The changes are not updated into the file. I do not know what I am doing wrong.
The XML is too long. The file has information about several activities. I am interested only in the activity with Id A04.
The initial value of the PlannedDuration is 16 and I changed it to 25.
XML File:
package modifyXML;
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.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;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXML{
public static void main(String[] args) {
File xmlfile = new File("C:/Users/dianitaf/Downloads/xml Files/CS_1.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(xmlfile);
document.getDocumentElement().normalize();
updateElementValue(document,"Id", "A04");
document.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("xmlfile"));
transformer.transform(source, result);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
e1.printStackTrace();
}
}
private static void updateElementValue(Document document, String textNodeName, String textNodeValue) {
NodeList Activity = document.getElementsByTagName("Activity");
Element act = null;
//loop for each activity
for(int i=0; i<Activity.getLength();i++){
Node activityNode = Activity.item(i);
if(activityNode.getNodeType() == Node.ELEMENT_NODE)
{
Element activityElement = (Element) activityNode;
NodeList textNodes = activityElement.getElementsByTagName(textNodeName);
if(textNodes.getLength() > 0)
{
if(textNodes.item(0).getTextContent().equalsIgnoreCase(textNodeValue))
{
System.out.println(textNodes.item(0).getTextContent());
System.out.println(activityElement.getElementsByTagName("Name").item(0).getTextContent());
act = (Element) Activity.item(i);
Node duration = act.getElementsByTagName("PlannedDuration").item(0).getFirstChild();
System.out.println("Initial Duration : " + act.getElementsByTagName("PlannedDuration").item(0).getTextContent()); act.getElementsByTagName("PlannedDuration").item(0).getTextContent();
duration.setTextContent("25");
System.out.println("Updaded Duration : " + act.getElementsByTagName("PlannedDuration").item(0).getTextContent());
}
}
}
}
}
}
XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><APIBusinessObjects>
<ProjectList>
<Project ObjectId="4627">
<Id>CS_1</Id>
<Name>Case Study No.1 Warehouse Project - CPM</Name>
</Project>
</ProjectList>
<Project>
<Activity>
<Id>A04</Id>
<Name>Nailers to Purlins</Name>
<PlannedDuration>16</PlannedDuration>
<StartDate>2018-12-26Te8:00:00</StartDate>
</Activity>
</Project>
</APIBusinessObjects>
Java:
package modifyXML;
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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ModifyXML {
public static void main(String[] args) {
File xmlfile = new File("D:\\delete\\test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(xmlfile);
document.getDocumentElement().normalize();
updateElementValue(document, "Id", "A04");
document.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(xmlfile);
transformer.transform(source, result);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
e1.printStackTrace();
}
}
private static void updateElementValue(Document document, String textNodeName, String textNodeValue) {
NodeList Activity = document.getElementsByTagName("Activity");
Element act = null;
// loop for each activity
for (int i = 0; i < Activity.getLength(); i++) {
Node activityNode = Activity.item(i);
if (activityNode.getNodeType() == Node.ELEMENT_NODE) {
Element activityElement = (Element) activityNode;
NodeList textNodes = activityElement.getElementsByTagName(textNodeName);
if (textNodes.getLength() > 0) {
if (textNodes.item(0).getTextContent().equalsIgnoreCase(textNodeValue)) {
System.out.println(textNodes.item(0).getTextContent());
System.out.println(activityElement.getElementsByTagName("Name").item(0).getTextContent());
act = (Element) Activity.item(i);
Node duration = act.getElementsByTagName("PlannedDuration").item(0).getFirstChild();
System.out.println("Initial Duration : "
+ act.getElementsByTagName("PlannedDuration").item(0).getTextContent());
act.getElementsByTagName("PlannedDuration").item(0).getTextContent();
duration.setTextContent("25");
System.out.println("Updaded Duration : "
+ act.getElementsByTagName("PlannedDuration").item(0).getTextContent());
}
}
}
}
}
}
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);
}
}
I have an xml as String
<color>
<name>black</name>
<color>
I want to add an attribute to root node and save a xml as String again.
<color id="1">
<name>black</name>
<color>
But I can't. Here is my code
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
String xml = "<color><name>black</name></color>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document document = builder.parse(is);
Element element = (Element) document.getFirstChild();
element.setAttribute("id", "1");
String result = document.toString();
System.out.println(result);
The output is [#document: null]. Help me please resolve my problem
You can not use document.toString() to get output. You need to convert document object back to xml string.
Please check following code. It will help to solve your problem.
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
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.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class test1 {
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException {
final String xmlStr = "<color><name>black</name></color>";
Document doc = convertStringToDocument(xmlStr);
String str = convertDocumentToString(doc);
System.out.println(str);
}
private static Document convertStringToDocument(String xmlStr)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlStr));
Document document = builder.parse(is);
Element element = (Element) document.getFirstChild();
element.setAttribute("id", "1");
String result = document.toString();
System.out.println(result);
return document;
}
private static String convertDocumentToString(Document doc) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
}
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 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);
}