简体   繁体   中英

Add nodes to an xml at runtime?

I am writing an application that must update parts of an already existing xml file based on a set of files in a directory. An example of this xml file can be seen below:

http://izpack.org/documentation/sample-install-definition.html

In the below scope a list of files is added and its specified if they should be "parsable" (used for parameter substitution):

  <packs>
    <pack name="Main Application" required="yes" installGroups="New Application" >
          <file src="post-install-tasks.bat" targetdir="$INSTALL_PATH"/>
          <file src="build.xml" targetdir="$INSTALL_PATH"/>
          <parsable targetfile="$INSTALL_PATH/post-install-tasks.bat"/>
          <parsable targetfile="$INSTALL_PATH/build.xml"/>
    </pack>
  </packs>

Now the number of files that must be added to this scope can change each time the application is run. To make this possible I have considered the following approach:

1) Read the whole xml into a org.w3c.dom.*; Document and add nodes based on result from reading the directory.

2) Somehow add the content from a .properties file to the scope. This way its possible to update the filelist without recompiling the code.

3) ??

Any suggestions on a good approach to this kind of task?

3) Overwrite the old file with your new, modified version. The DOM parsers keep comments intact, but you could end up with formatting differences. In order to write to a file, do:

Source source = new DOMSource(doc);
File file = new File(filename);
Result result = new StreamResult(file); 
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result); 

if there's a chance that your XML configuration might be of significant size, then it is really not good to go ahead with a DOM based approach [due to the associated memory footprint of loading a large XML document]

you should take a look at StaX . it has a highly optimised approach for both parsing and writing XML documents.

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