javaxmlxpathapache-commons-config

How to add new XML element to the root element of a hierarchical XML configuration with addProperty() in Apache Commons Configuration?


So I tried it with XPathExpressionEngine but it's not working. My XML file looks like this.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<omg>
  <configurationCreated>24/05/20 00:43:42</configurationCreated>
</omg>

I want the end result to be this.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<omg>
  <configurationCreated>24/05/20 00:43:42</configurationCreated>
  <newElement />
</omg>

I tried this.

Parameters parameters = new Parameters();

FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class)
    .configure(parameters
        .xml()
        .setFileName("mahfile.xml")
        .setExpressionEngine(new XPathExpressionEngine()));

builder.setAutoSave(true);

try {
  configuration = builder.getConfiguration();
} catch (ConfigurationException e) {
  return;
}

configuration.addProperty("omg", "newElement");

The result however is this (what the actual heck).

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<omg>
  <configurationCreated>24/05/20 00:43:42</configurationCreated>
  <omg>newElement</omg>
</omg>

I also tried the following XPath expressions with addProperty() method but nothing is working. How do I do this correctly? Documentation is not helpful here.

I think this is not possible, however an expression like configuration.addProperty("newElement/childElement/name", "value") creates the new element but with a child in it.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<omg>
  <configurationCreated>24/05/20 00:43:42</configurationCreated>
  <newElement>
    <childElement>
       <name>value</name>
    </childElement>
  </newElement>
</omg>

On a side note: I additionally tried configuration.getDocument().createElement("newElement") but this does not save my configuration file automatically.


Solution

  • According to the documentation page you linked, and to this page you can achieve your goal using:

    configuration.addProperty("newElement", "");
    

    You don't have to specify any "structure" in the first parameter since you're adding to the root element and since you are adding one element with no children, and the second parameter is the value of that element, in your case, it's an empty value.