0

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();
    }
  }

}

5 Answers5

1

The result share as below: This is just a dummy test as i have done. I wonder how to save it in a text file?

TeacherName 
--------------------------------
Sara 
Marry
John
0

You made this like here

// 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("C:\\file.xml"));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

More you can find on: https://mkyong.com/java/how-to-create-xml-file-in-java-dom/

As alternative you can use the transform method to pass it into StringWriter. the you can made this because you have an string

StringWriter sw = new StrinWriter();
transformer.transform(source, new StreamResult(sw));
FileWriter fw = new FileWriter("file.txt")
fw.write(sw.toString();
fw.close()
Strider
  • 134
  • 7
  • Is it possible to let me know , where in the source code i should add it? – Sara Mirabi May 09 '20 at 12:02
  • I would add this after parsiing and building the xmltree – Strider May 09 '20 at 12:09
  • It has been added below: – Sara Mirabi May 09 '20 at 12:28
  • Ok, i've tested thic code, i have comment out all code which goes over the xmltree. In short, the wile was written. maybe the file path mus be an absolute path. – Strider May 09 '20 at 12:41
  • What i forget to say is that "~" is an a shortpath on linux, which java does not understand. I think it is better to handle "~" by replacing ith with System.getProperty("user.home") which gives you an abyolute path based on your home directory of the current user :) – Strider May 09 '20 at 12:48
0

Here you are:

    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;
    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

    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);
// 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("~/Downloads/file.xml"));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);
     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();
        }
      }

    }
0

Here the code with absolute path:

File fXmlFile = new File("/home/user/Downloads/Teacher.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("/home/user/Downloads/file.xml"));
        transformer.transform(source, result);

And here we replace the "~" :

File fXmlFile = new File("~/Downloads/file.xml".replaceFirst("^~", System.getProperty("user.home")));
            DocumentBuilderFactory dbFactory = 
  DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("~/Downloads/file.xml".replaceFirst("^~", System.getProperty("user.home"))));
            transformer.transform(source, result);
Strider
  • 134
  • 7
  • I checked your code. I just want to save the result in a text file. I cant find .txt in any path. My code which i shared above is working fine, in eclipse i am seeing the result in console now i want to save it in a txt format on my desktop or downloads for example. I am so new with java and i used filewriter but it save a blank text file not my results :-( – Sara Mirabi May 10 '20 at 04:39
  • Ok, if i understand you want to write the output in your console into your file? – Strider May 10 '20 at 10:42
  • Exactly I want to have the result in a text file. – Sara Mirabi May 10 '20 at 10:52
  • Ok, then i have to know how the result should lookl in you txt file. That's because to know where we can start to collect the results and when we can save it to a file. Can you post me a dummy xml file, too? – Strider May 10 '20 at 11:04
  • Yes the result look like this: – Sara Mirabi May 10 '20 at 11:40
0

Ok, based on you answer i have this code for you, i have been used a Strin builder to store the output and write them with an FileWriter to an txt file

 public static void main(String[] args)
{

    try
    {

        File fXmlFile = new File("~/Downloads/Teacher.xml".replaceFirst("^~", System.getProperty("user.home")));
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);



        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        //Teacher name tags

        StringBuilder result = new StringBuilder(doc.getDocumentElement().getNodeName() + "\n----------------------------\n");

        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());
                result.append(String.format("%s\n", eElement.getElementsByTagName("Name").item(0).getTextContent()));
            }
        }

        FileWriter writer = new FileWriter(new File("~/Downloads/file.xml".replaceFirst("^~", System.getProperty("user.home"))));
        writer.write(result.toString());
        writer.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

I've tested thic code and it runs :)

Strider
  • 134
  • 7