2

For the following XML:

<properties>
  <entry key="foo">bar</entry>
</properties>

I can update exiting entry with attribute "foo" with the following augeas command:

set /files/test.xml/properties/entry[#attribute/key='foo']/#text bar2

Is there augeas command(s) to create a new node (with key attribute) if there is no existing entry with the input attribute, and update existing if entry already exists with the input attribute? I tried the following:

set /files/test.xml/properties/entry[#attribute/key='hello']/#text world

But this only results in the following, without attribute:

<properties>
  <entry key="foo">bar2</entry>
  <entry>world</entry>
</properties>
fruitJuice
  • 1,281
  • 2
  • 11
  • 22
  • possible duplicate of [Issues adding attribute to XML root node via augeas](http://stackoverflow.com/questions/21289801/issues-adding-attribute-to-xml-root-node-via-augeas) – kkamil May 06 '15 at 19:02

2 Answers2

2

/files/test.xml/properties/entry[#attribute/key='hello']/#text doesn't match any node, so Augeas creates a new node. If you want to update both values.

Apparently, you want to keep only one entry node and set both its text and key attribute:

defnode entry /files/test.xml/properties/entry[#attribute/key="foo"]
set $entry/#attribute/key 'hello'
set $entry/#text 'world'
raphink
  • 3,625
  • 1
  • 28
  • 39
0

Assuming you want this output:

<properties>
    <entry key="foo">bar</entry>
    <entry key="hello">world</entry>
</properties>

The following code should do the trick:

set /augeas/load/Xml/incl[2] /path/to/file.xml
load
defvar properties "/files/path/to/file.xml/properties"
set $properties/entry[last()+1]/#attribute/key "hello"
set $properties/entry[last()]/#text "world"
save
Marcel
  • 5
  • 4
  • This works but is not idempotent. Every run of this script will create a new entry with key "hello" and text "world". – raphink Aug 06 '20 at 20:04