As i am new to java i need some help of modifying xml file using java .i am having some xml files in a folder. i want to add a child tag with another child tag.i have tried to get all file by using File. and for parsing and modification purpose i am using DocumentBuildFactory and Element. but at parse method of DocumentBuilder the file is not coming its showing null.
Input:-
<Student>
<personal-details>
<name>abc</name>
<age>21</age>
</personal-details>
<address>
<zip>560037</zip>
</address>
</Student>
i want to add a child element inside the address tag and expect output like below:-
Output:-
<Student>
<personal-details>
<name>abc</name>
<age>21</age>
</personal-details>
<address>
<place>
<line1>some lane</line1>
</place>
<zip>560037</zip>
</address>
</Student>
the java code i have written is below
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class AddTag {
public static void main(String[] args) {
File folder = new File("C:\\Users\\Desktop\\xmlfiles\\");
File listOfFiles [] =folder.listFiles();
String fileName = null;
for(int i=0;i<listOfFiles.length;i++)
{
fileName = listOfFiles[i].getName();
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(folder+"\\"+fileName);
System.out.println(doc); // op:-[#document: null]
Node address = doc.getElementsByTagName("address").item(0);
Element place = doc.createElement("place");
place.appendChild(doc.createElement("line1").appendChild(doc.createTextNode("some lane")));
address.appendChild(place);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(folder+"\\"+fileName));
transformer.transform(source, result);
System.out.println("Done");
}catch(Exception e){
}
}
}
}
but i am getting out put like below without line1 tag:-
<Student>
<personal-details>
<name>abc</name>
<age>21</age>
</personal-details>
<address>
<zip>560037</zip>
<place>some lane</place>
</address>
</Student>