How to output name, file type and extension of an xml file to another xml

I have a java class that applies xslt to all xml files in a directory and does the conversion on every xml file it finds and prints out the full filename.

My question is how to create xml (Files.xml) which will have the following format and then output the file name, file type and file extension in Files.xml?

<files>
  <file>
    <name> ThisFile </name>
    <type> xml </type>
    <extension> .xml </extension>
  </file>

  <file>
    <name> AnotherFile </name>
    <type> xml </type>
    <extension> .xml </extension>
  </file>

  etc....
</files>

      

Thanks again for any help I get!

+1


source to share


1 answer


I would recommend using a serialization utility like JAXB or XStream to serialize the file model directly, but I leave a small example here that builds a document from scratch.

public void serializeXmlFiles(ArrayList<File> files) throws ParserConfigurationException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    Element filesElement = doc.createElement("files");
    doc.appendChild(filesElement);

    for (File file : files) {
        Element fileElement = doc.createElement("file");
        Element nameElement = doc.createElement("name");
        nameElement.setTextContent(file.getName());
        Element typeElement = doc.createElement("type");
        typeElement.setTextContent("xml");
        Element extElement = doc.createElement("extension");
        extElement.setTextContent(".xml");

        fileElement.appendChild(nameElement);
        fileElement.appendChild(typeElement);
        fileElement.appendChild(extElement);
        filesElement.appendChild(fileElement);
    }

    saveXMLDocument("files.xml", doc);
}

public boolean saveXMLDocument(String fileName, Document doc) throws TransformerException {
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos;
    Transformer transformer;
    try {
        fos = new FileOutputStream(xmlOutputFile);
    } catch (FileNotFoundException e) {
        return false;
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    transformer = transformerFactory.newTransformer();

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fos);

    transformer.transform(source, result);
    return true;
}

      



Hope it helps.

+1


source







All Articles