how to update existing or create new XML node with Augeas

这一生的挚爱 提交于 2020-08-09 01:37:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!