简体   繁体   中英

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.

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM