apache-commons-config

Commons Config - How to delete a node?


I have an xml configuration file built using commons config (XMLConfiguration)

<servers>
  <server>
   <name>Google</name>
   <address>www.google.com</address>
  <server>
  <server>
   <name>Yahoo</name>
   <address>www.yahoo.com</address>
  </server>
</servers>

I can obtain the correct node to update by getting a list of servers like this:

List<HierarchicalConfiguration> serverList = config.configurationsAt("server");
for(HierarchicalConfiguration server : serverList){
  if(server.getString("name").equals("Google")){
    //now I have the node I want to work with
    // and I can update it but I cannot delete it completely
  }

I don't understand how to delete the node. If I call server.clear(), the data disappears, but an empty node remains.

<servers>
  <server/>
  <server>
   <name>Yahoo</name>
   <address>www.yahoo.com</address>
  </server>
</servers>

What I'd like to do is remove the node completely.


Solution

  • I did find a way to do it. Not sure if it's the best way, but for anybody else looking:

    You need to find the index of the node, then delete it by address using XMLConfiguration.clearProperty() or XMLConfiguration.clearTree(). Here is an example using the configuration file in my question:

    //config is my XMLConfiguration object

    List<HierarchicalConfiguration> serverList = config.configurationsAt("server");
    Integer index = 0;
    
    for(HierarchicalConfiguration server : serverList){
      if(server.getString("name").equals("Google")){
        //for Google, this evaluates to "server(0)", for Yahoo, "server(1)" 
        config.clearTree("server("+Integer.toString(index)+")");
      }
      index++; //increment the index at the end of each loop
    }
    //don't forget to write changes to file
    config.save();