问题
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>
回答1:
/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'
回答2:
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
来源:https://stackoverflow.com/questions/30083343/how-to-update-existing-or-create-new-xml-node-with-augeas