简体   繁体   English

在运行时将节点添加到xml?

[英]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. 我正在编写一个应用程序,该应用程序必须根据目录中的一组文件来更新已经存在的xml文件的部分。 An example of this xml file can be seen below: 可以在下面看到此xml文件的示例:

http://izpack.org/documentation/sample-install-definition.html 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.*; 1)将整个xml读入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. 2)以某种方式将.properties文件中的内容添加到范围中。 This way its possible to update the filelist without recompiling the code. 这样就可以在不重新编译代码的情况下更新文件列表。

3) ?? 3)??

Any suggestions on a good approach to this kind of task? 有什么建议可以很好地解决此类任务吗?

3) Overwrite the old file with your new, modified version. 3)用修改后的新版本覆盖旧文件。 The DOM parsers keep comments intact, but you could end up with formatting differences. DOM解析器使注释完整无损,但最终可能会出现格式差异。 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] 如果您的XML配置可能有很大的规模,那么继续使用基于DOM的方法确实不好(由于加载大XML文档的相关内存占用)

you should take a look at StaX . 您应该看看StaX it has a highly optimised approach for both parsing and writing XML documents. 它具有用于解析和编写XML文档的高度优化的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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