tags:

views:

113

answers:

1

Hi folks,

I have a java class that applies an xslt to all xml files in a directory and performs a transformation on every xml it finds and prints out the complete filename.

My question is how would I create an xml (Files.xml),which would have the following format, and then ouputs the file name, file type and file extension to 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>

Once again I appreciate any and all help I get!

+1  A: 

I would recommend using a serialization utility like JAXB or XStream to serialize the file model directly but I leave you here a small sample that builds the 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.

bruno conde