1

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.

Steve Kallestad
  • 3,484
  • 2
  • 23
  • 31

2 Answers2

1

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();
Steve Kallestad
  • 3,484
  • 2
  • 23
  • 31
0

You can also use XPATH:

config.clearTree("servers/server[name='Google']");
Phoenix
  • 41
  • 3