I retrieved my needful data from XML tags. I used relative packages in this regard. Now I want to save the result in a .txt file but I don't know how to use FileWriter in my code? I tried several times but I got a blank text file without the printed result in the console. Anyone can help me in saving the result in txt?
package XMLConvertor;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class Sample {
public static void main(String argv[]) {
try {
//SourceFile
File fXmlFile = new File("~/Downloads/Teacher.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//normalizing doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
//Teacher name tags
NodeList nList = doc.getElementsByTagName("TeacherName");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Name: " + eElement.getElementsByTagName("Name").item(0).getTextContent());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}