damien535
damien535

Reputation: 637

Creating xml from with java

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

What I want to do now is create an xml containing the file names and file format types. The format should be something like;

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

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

Where for every file it finds in the directory it creates a new <file>.

Any help is truely appreciated.

Upvotes: 1

Views: 430

Answers (4)

frankodwyer
frankodwyer

Reputation: 14048

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

In this case it probably doesn't arise and you will get away without it, however if you ever port this code to reuse in another case, you may be bitten by this. So you might want to look at an XMLWriter class which will do all the escaping work for you.

Upvotes: 1

Paulo Guedes
Paulo Guedes

Reputation: 7259

Have a look at DOM and ECS. The following example was adapted to you requirements from here:

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499840

Use an XML library. There are plenty around, and the third party ones are almost all easier to use than the built-in DOM API in Java. Last time I used it, JDom was pretty good. (I haven't had to do much 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);

Upvotes: 10

Vinze
Vinze

Reputation: 2539

Well just use a 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());

Upvotes: 0

Related Questions