1

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>

2020欧洲杯时间表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? is not helpful here.

  • configuration.addProperty("/omg", "newElement");
  • configuration.addProperty("//omg", "newElement");
  • configuration.addProperty("newElement", null);
  • configuration.addProperty("omg newElement", null);

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.

1

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

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

2020欧洲杯时间表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.

| improve this answer | |
  • Nope. Tried that. Doesn't work. – Tony Stark May 25 at 17:37
  • What result do you get? Or what error if any? – Ayoub_B May 25 at 19:20
  • Not sure why but after doing Maven --> Reimport, your solution works. Thanks. – Tony Stark May 25 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy2020欧洲杯时间表

Not the answer you're looking for? Browse other questions tagged or ask your own question.