Generating xml with java

I need your experience again. I have a java class that looks for a directory for xml files (displays the files it finds in the eclipse console window), applies the specified xslt to them, and sends the output to the directory.

Now I want to create an xml containing file names and file types. The format should be something like this:

<file>
      <fileName>         </fileName>
      <fileType>       </fileType>
</file>

<file>
     <fileName>         </fileName>
     <fileType>       </fileType>
</file>

      

Where for each found file in the directory a new one is created <file>

.

Any help is really appreciated.

+1


source to share


4 answers


Have a look at the DOM and ECS. The following example has been adapted to your requirements from here :



XMLDocument document = new XMLDocument();
for (File f : files) {
    document.addElement( new XML("file")
        .addXMLAttribute("fileName", file.getName())
        .addXMLAttribute("fileType", file.getType())
      )
    );
}

      

+3


source


Use an XML library. There are many of them, and third-party ones are almost all easier to use than the built-in DOM API in Java. JDom was pretty good the last time I used it . (I didn't have to do a lot of XML recently.)

Something like:



Element rootElement = new Element("root"); // You didn't show what this should be
Document document = new Document(rootElement);

for (Whatever file : files)
{
    Element fileElement = new Element("file");
    fileElement.addContent(new Element("fileName").addContent(file.getName());
    fileElement.addContent(new Element("fileType").addContent(file.getType());
}

String xml = XMLOutputter.outputString(document);

      

+10


source


You can use the StringBuilder approach suggested by Vinze, but one caveat is that you will need to make sure your filenames do not contain XML special characters, and avoid them if they do (e.g. replace <with & lt ;, and deal with quotes accordingly).

In this case, it probably does not occur and you do without it, however, if you ever port this code for reuse in another case, you might be bitten by this. As such, you might want to take a look at the XMLWriter class that will do its best for you.

+1


source


Well just use StringBuilder:

StringBuilder builder = new StringBuilder();
for(File f : files) {
    builder.append("<file>\n\t<fileName>").append(f.getName).append("</fileName>\n)";
    [...]
}
System.out.println(builder.toString());

      

0


source







All Articles